I'm trying to pass a member function as an argument to a template function. I have read all the threads in Stackoverflow about passing member functions as arguments to other functions. But, somehow I don't get this simple thing to work:
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));
}
The error message I receive is:
no matching member function for call to 'registerCallback'
I have tried to solve this for a long time. I would be very grateful if someone can point me out what is wrong.
The callback that must be registered does not have any parameters.
std::function< T() >
However, you try to register a callback which accepts a single parameter.
std::bind(&Class::member, this, std::placeholders::_1)
Furthermore, the Class::member
function doesn't have any parameters.
Try this:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.