成员函数指针不太正确
我有一个模板化的 SpecializedRedBlackTree 类。
我的月课不是。
在我的 Month 类中,我有一个私有成员,它是 SpecializedRedBlackTree 的一个实例:
SpecialisedRedBlackTree<Day> m_windSpeedTree;
如您所见,它将采用 Day 类/对象(请纠正我的任何错误术语)。
在我的 Month 类中,我有一个方法将方法函数指针传递给该方法:
bool Month::CompareWindSpeed(Day a, Day b) {
return ( a.GetData(WIND_SPEED_CODE) < b.GetData(WIND_SPEED_CODE)? true : false);
}
bool (Month::*myFuncPtr)(Day, Day);
myFuncPtr = &Month::CompareWindSpeed;
m_windSpeedTree.Insert(dayReading, myFuncPtr);
但是因为我将 bool (Day, Day) 指针传递给模板类,期望 bool (T, T)
T 成为该方法的一部分... . 模板
Error 1 error C2664: 'SpecialisedRedBlackTree<T>::Insert' : cannot convert parameter 2 from 'bool (__thiscall Month::* )(Day,Day)' to 'bool (__cdecl *)(T,T)'
有什么建议吗?
I have a SpecialisedRedBlackTree class that is templated.
My Month class is not.
In my Month class I have a private member which is an instance of SpecialisedRedBlackTree:
SpecialisedRedBlackTree<Day> m_windSpeedTree;
As you can see it will take the Day class/object (please correct me on any terms I get wrong).
In my Month class, I have a method passing a method function pointer to this method:
bool Month::CompareWindSpeed(Day a, Day b) {
return ( a.GetData(WIND_SPEED_CODE) < b.GetData(WIND_SPEED_CODE)? true : false);
}
bool (Month::*myFuncPtr)(Day, Day);
myFuncPtr = &Month::CompareWindSpeed;
m_windSpeedTree.Insert(dayReading, myFuncPtr);
But because I am passing a bool (Day, Day) pointer to a templated class expecting bool (T, T)
T being part of this .... template
Error 1 error C2664: 'SpecialisedRedBlackTree<T>::Insert' : cannot convert parameter 2 from 'bool (__thiscall Month::* )(Day,Day)' to 'bool (__cdecl *)(T,T)'
Any advice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此时的问题不在于该类是模板化的,而是您在需要非成员函数的地方传递了成员函数。
您可以:
CompareWindSpeed()
设为自由函数或静态成员函数Insert()
获取成员函数指针和实例指针tr1::function
或boost::function
或类似的包装器而不是函数指针The problem at this point is not that the class is templated, but that you are passing a member-function where a non-member function is expected.
You could:
CompareWindSpeed()
a free function or a static member functionInsert()
take a member function pointer and an instance pointertr1::function
orboost::function
or similar wrappers instead of function pointers就函数指针而言,对象的函数与普通函数不同。您需要存储对对象本身的引用以及函数指针才能调用它。
例如,一个存储函数和对象指针的类:
要使用它,您将执行以下操作:
要触发函数调用:
A function of an object is not the same as a normal function in regards to function pointers. You need to store a reference to the object it self and also the function pointer to be able to call it.
For Example a class to store the functior and object pointer:
To use it you would do this:
To trigger the function call: