Reputation: 153
My example below uses variadic templates to register a function inside a class. Registering a single function works but what about class member functions? I tried std::bind but this expects placeholders which is not an option because I don't know the number of arguments. Is there a simple way doing this in C++11 or am I forced to implement the register function for every amount of arguments?
template<typename TReturn, typename... TArgs>
class Func {
std::function<TReturn (TArgs...)> fn;
template<typename TFunction, typename TObject>
bool register(TFunction f, TObject obj){
}
bool register(std::function<TReturn (TArgs...)> f){
fn = f;
return true;
}
}
Upvotes: 2
Views: 1205
Reputation: 16737
Create a lambda function with the required signature and construct the std::function
object from it.
template<typename TReturn, typename... TArgs>
class Func {
std::function<TReturn (TArgs...)> fn;
template<typename TFunction, typename TObject>
bool Register(TFunction f, TObject obj){
fn = [obj](TArgs... args){return (obj.*f)(args...);};
return true;
}
bool Register(std::function<TReturn (TArgs...)> f){
fn = f;
return true;
}
}
(Note : Member function pointers need to be used with a corresponding object, object reference or a pointer to an object of the appropriate class. If TObject
is value-like, the member function call syntax would be (obj.*f)
. If TObject
is pointer-like, the syntax would be (obj->*f)
.)
Upvotes: 3