[英]Passing a function pointer in to templated class
我的问题很简单......我有一个模板化的二叉搜索树。 当调用构造函数时,我需要能够让用户传入比较 function 。 我的代码一直对我大喊大叫,直到我也将用户定义的 function 模板化(在驱动程序中)。 这打破了我对模板如何工作的直觉。 这让我想知道我的代码是否没有像我预期的那样模板化。 I'm just curious if it is normal to have a user template their functions when declaring a class object that is templated (specially when that object requires a user defined function to be passed in). 如果这不正常,那么我知道我的代码有问题。
这是我之前遇到的错误。 那些“未声明的标识符”只是第 93 行的一个错误的结果。这是我试图创建 class 实例的地方。
//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;
};
我认为您的问题在于您对 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);
希望这可以帮助。 如果我对您的问题有误解,请告诉我。
我相信部分问题是您的 arguments 是整数,当它们似乎应该是 T 时,以匹配用户定义的类型。 假设它们是 int 可以进行测试,但如果需要任何其他数据类型,则不会成立。 如果是这种情况,将其模板化是有意义的,因为 function 正在有效地转换到您的 header 文件中,该文件似乎是模板化的。 当然,我对此比较陌生,所以如果我犯了逻辑错误,请告诉我!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.