This might seem stupid but please...
class Button{
public:
void func();
void Button(void func()){
//Do something.
//Like if(something){
func();
}
}
};
How do I pass func() as a parameter to Button()?
Thanks in advance!
CodePudding user response:
func cannot be passed into Button as an argument. The parameter of Button is a pointer to function, and pointers to functions cannot point to non-static member functions. func is a non-static member function and it cannot be pointed by a pointer to function.
Solutions:
- Accept a pointer to member function as the parameter instead of a pointer to function.
- Make
funca non-member function or a static member function which can be pointed by a pointer to function.
CodePudding user response:
In C 11 and later, you can use std::function, eg:
#include <functional>
class Button{
public:
void Button(std::function<void()> func){
if (something){
func();
}
}
};
This way, you can equally accept any callable type, whether that be a standalone function, a lambda, the result of std::bind(), etc.
