我正在尝试将成员函数作为参数传递给模板函数。我已经阅读了 Stackoverflow 中关于将成员函数作为参数传递给其他函数的所有线程。但是,不知何故,我无法让这个简单的东西发挥作用:
template <typename T>
T Class::registerCallback(std::function<T()> callback) {
// do something
}
bool Class::member() {
return true;
}
void Class::method() {
registerCallback(std::bind(&Class::member, this, std::placeholders::_1));
}
我收到的错误信息是:
no matching member function for call to 'registerCallback'
我已经尝试了很长时间来解决这个问题。如果有人能指出我哪里出了问题,我将不胜感激。
最佳答案
必须注册的回调没有任何参数。
std::function< T() >
但是,您尝试注册一个接受单个参数的回调。
std::bind(&Class::member, this, std::placeholders::_1)
此外,Class::member
函数没有任何参数。
试试这个:
class Class
{
public:
// I'm not sure why this was returning a 'T' changed to 'void'
template<typename T>
void registerCallback(std::function<T()> callback)
{
// do something
}
void method()
{
// The 'member' function doesn't have any parameters so '_1' was removed
registerCallback<bool>(std::bind(&Class::member, this));
}
// The callback is supposed to return 'T' so I changed this from 'bool'
bool member()
{
return true;
}
};
int main()
{
Class<bool> c;
c.method();
return 0;
}
关于c++ - 将成员函数作为回调传递给模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29383346/