Skip to content

Instantly share code, notes, and snippets.

@inlinechan
Last active May 12, 2016 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inlinechan/54c742c28a11f418306aee6e718e9af9 to your computer and use it in GitHub Desktop.
Save inlinechan/54c742c28a11f418306aee6e718e9af9 to your computer and use it in GitHub Desktop.
functor
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