Last active
May 12, 2016 14:01
-
-
Save inlinechan/54c742c28a11f418306aee6e718e9af9 to your computer and use it in GitHub Desktop.
functor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename Sig> | |
class Function; | |
template <typename R, typename... Args> | |
class Function<R(Args...)> { | |
public: | |
typedef R(*Runtype)(Args...); | |
Function(Runtype f) : f_(f) {} | |
R operator()(Args... args) { | |
return (*f_)(args...); | |
} | |
private: | |
Runtype f_; | |
}; | |
template <typename R, typename T, typename... Args> | |
class Function<R(T::*)(Args...)> { | |
public: | |
// typedef R(*RunType)(T*, Args...); | |
Function(T* object, R(T::*method)(Args...)) | |
: object_(object), method_(method) {} | |
R operator()(Args... args) { | |
return (object_->*method_)(args...); | |
} | |
private: | |
T* object_; | |
R (T::*method_)(Args...); | |
}; | |
void func() {} | |
int func3(int) { return 1; } | |
struct Foo { | |
void bar(int v) { std::cout << "Foo::bar(" << v << ")" << std::endl; } | |
}; | |
void test_function() { | |
Function<void()> f1(&func); | |
f1(); | |
Function<int(int)> f3(&func3); | |
f3(1); | |
Foo foo; | |
Function<void(Foo::*)(int)> f4(&foo, &Foo::bar); | |
f4(1); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment