Last active
December 16, 2015 13:59
-
-
Save jeetsukumaran/5445996 to your computer and use it in GitHub Desktop.
Making functions: How to provide a simple interface when working with std::function
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
// See: http://kbokonseriousstuff.blogspot.fr/2013/04/making-functions-how-to-provide-simple.html?spref=tw | |
// From: http://coliru.stacked-crooked.com/view?id=665b6505b8cbe3631604d8300f9e6b27-50d9cfc8a1d350e7409e81e87c2653ba | |
#include <iostream> | |
#include <functional> | |
// Only takes std::functions | |
template<typename R, typename... P> | |
void do_something(std::function<R(P...)> &func) { | |
std::cout << &func << std::endl; | |
} | |
struct not_pointer_to_member_function{}; | |
template<typename T> | |
struct pointer_to_member_function_traits { | |
typedef not_pointer_to_member_function type; | |
}; | |
template<typename C, typename R, typename... P> | |
struct pointer_to_member_function_traits<R (C::*)(P...) const> { | |
typedef std::function<R(P...)> type; | |
}; | |
struct not_callable{}; | |
template<typename C> | |
struct callable_traits { | |
typedef typename pointer_to_member_function_traits<decltype(&C::operator())>::type type; | |
}; | |
template<typename R, typename... P> | |
struct callable_traits<R(P...)> { | |
typedef std::function<R(P...)> type; | |
}; | |
template<typename Func> | |
typename callable_traits<Func>::type | |
make_function(const Func &func) { | |
return func; | |
} | |
void abc(){} | |
struct fo_abc { | |
void operator()() const {} | |
}; | |
int main () { | |
std::function<void(int, int)> lamarck = [&](int a, int b){ std::cout << a << b; }; | |
auto func = make_function([](){}); // lambda | |
auto func2 = make_function(abc); // free function | |
auto func3 = make_function(fo_abc()); // function object | |
do_something(func); | |
do_something(func2); | |
do_something(func3); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment