我的问题很简单...我有一个模板化的二叉搜索树。我需要能够在调用构造函数时让用户传递一个compare函数。我的代码一直在大吼大叫,直到我也将用户定义的函数模板化(在驱动程序中)。这打破了我对模板工作原理的直觉。这使我想知道我的代码是否未按预期进行模板化。我只是想知道,当声明一个已模板化的类对象时(特别是当该对象需要传递用户定义的函数时),让用户使用其函数模板是正常的。如果这不正常,那么我知道我的代码有误。
这是我之前遇到的错误。这些“未声明的标识符”仅是第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;
};
我写了一些代码,我认为它可以模仿您的用例。它在我的机器上编译:
//header file
template <typename T>
class TemplatedClass {
public:
TemplatedClass(int(*compFunction)(const T, const T)) :
funcCompare(compFunction)
{}
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);
希望这会有所帮助。如果我对您的问题有误解,请告诉我。