Created
January 21, 2019 23:34
-
-
Save Qix-/5678d99b74235cdfecb063860429903f to your computer and use it in GitHub Desktop.
Accepting any callable as a parameter to a variadic template for any pack of argument types
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
#include <iostream> | |
#include <string> | |
#include <functional> | |
#include <tuple> | |
#include <type_traits> | |
using namespace std; | |
// This voodoo brought to you by the legendary JLBorges | |
// http://www.cplusplus.com/forum/general/223816/#msg1025150 | |
namespace detail // EDIT: make it an implementation detail | |
{ | |
template < typename T > struct deduce_type ; | |
template < typename RETURN_TYPE, typename CLASS_TYPE, typename... ARGS > | |
struct deduce_type< RETURN_TYPE(CLASS_TYPE::*)(ARGS...) const > | |
{ using type = std::function< RETURN_TYPE(ARGS...) > ; }; | |
} | |
template <typename... Args> | |
void make_function(function<void(Args...)> fn) { | |
fn(10); | |
} | |
template <typename T> | |
void make_function(T const &fn) { | |
using foo = typename detail::deduce_type< decltype( &T::operator() ) >::type; | |
foo fn2 = fn; | |
make_function(fn2); | |
} | |
template <typename... Args> | |
void make_function(void (*fn)(Args...)) { | |
function<void(Args...)> sfn = fn; | |
make_function(sfn); | |
} | |
static void foo_bar(int a) { | |
cout << "static fn: " << a << endl; | |
} | |
int main() { | |
make_function([](int a) { cout << "lambda: " << a << endl; }); | |
function<void(int)> fn = [](int a) { cout << "function: " << a << endl; }; | |
make_function(fn); | |
make_function(&foo_bar); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment