2015-04-01 107 views
0

我试图将成员函数作为参数传递给模板函数。我已经阅读了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' 

我试图解决这个问题很长一段时间。如果有人能指出我出了什么问题,我将非常感激。

+0

是'Class'模板或者它只是有一个模板成员函数? – 2015-04-01 05:45:02

+0

只是一个模板成员函数。 – einstein 2015-04-01 05:47:15

+0

@JamesAdkison我解决了它只是提供了类型registerCallback (std :: bind(&Class :: member,this,std :: placeholders :: _ 1)); – einstein 2015-04-01 05:52:45

回答

1

必须注册的回调没有任何参数。

的std ::函数< T()>

然而,试图注册它接受一个参数的回调。

的std ::绑定(&类::构件,为此,性病::占位符:: _ 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; 
} 
+0

但我不想设置模板类?有没有解决方案,我可以设置模板方法?我也删除了'std :: placeholders :: _ 1',仍然给我同样的错误。 – einstein 2015-04-01 05:46:17

+0

@einstein我以为我看到了将所有函数定义为模板的原始问题......无论如何,我已经更新了答案。 – 2015-04-01 05:50:47

+0

谢谢@詹姆斯! – einstein 2015-04-01 05:53:28

相关问题