将函数指针传递给模板化类

时间:2019-10-15 04:12:02

标签: c++ templates function-pointers

我的问题很简单...我有一个模板化的二进制搜索树。我需要能够在调用构造函数时让用户传递一个compare函数。在我也将用户定义的函数(在驱动程序中)模板化之前,我的代码一直在大吼大叫。这打破了我对模板工作原理的直觉。这使我想知道我的代码是否未按预期进行模板化。我只是想知道,在声明一个已模板化的类对象时(特别是当该对象需要传递用户定义的函数时)让用户使用其函数模板是正常的。如果这不正常,那么我知道我的代码有误。 enter image description here

这是我之前遇到的错误。这些“未声明的标识符”仅是第93行出现一个错误的结果。这是我试图在其中创建类的实例的地方。

//Part of driver program. 
//Not sure why code doesn't work without template <typename T> 

template <typename T>
int compare(const int data, const int nodeData) 
//User defined compare function. Takes two values and compares them and returns a -1, 0, or 1 if it is less than equal to or greater than respectively. 
{
    int returnValue; //The value that will be returned. 
    if (data < nodeData)
    {
        returnValue = -1;
    }
    else if (data > nodeData)
    {
        returnValue = 1;
    }
    else
    {
        returnValue = 0;
    }
    return(returnValue);
}
//Now for the code that is inside my class. 
//The following is my decoration for the function pointer within my class.
//////////////
int (*funcCompare)(T i, T j); 
////////////////

//And lastly here is my constructor for my class 
    SplayTree(int(*compFunction)(const T, const T)) //Constructor that takes a pointer to a comparison function as an arugment. 
    {
        funcCompare = compFunction;
    };

2 个答案:

答案 0 :(得分:0)

我认为您的问题在于myTree的初始化。我写了一些我想模仿您的用例的代码。我相信最后一行尤其可以解决您的问题:

    //header file
    template <typename T>
    class TemplatedClass {
    public:
        TemplatedClass(int(*compFunction)(const T, const T)) :
            funcCompare(compFunction)
        {}
    private:
        int (*funcCompare)(const T i, const T j);
    };
    /////////////////////////////////////////////////////////////
    //compare function
    int compare(const int data, const int nodeData)
    {
        int returnValue; 
        if (data < nodeData)
        {
            returnValue = -1;
        }
        else if (data > nodeData)
        {
            returnValue = 1;
        }
        else
        {
            returnValue = 0;
        }
        return(returnValue);
    }
    //////////////////////////////////////////////////////////////
    //initialization
    TemplatedClass<int> tc(compare);

希望这会有所帮助。如果我对您的问题有误解,请告诉我。

答案 1 :(得分:0)

我认为部分问题是您的参数是整数,似乎它们应该为T,以匹配用户定义的类型。假设它们是int可以进行测试,但是如果需要任何其他数据类型,则不会保留它们。如果真是这样,将其模板化是有意义的,因为该函数已有效地转置到您的似乎是模板化的头文件中。当然,我对此还比较陌生,所以如果我犯了一个逻辑错误,请告诉我!