Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Complete Over-Use of Functor Templates (Academic Experiment)
#include <functional> #include <iostream> #include <vector> struct base_functor { virtual ~base_functor() {} virtual void operator()() = 0; }; template< typename TARGET, typename RESULT, typename... ARGS> struct derived_functor : base_functor { derived_functor(TARGET* ptr, RESULT (TARGET::*pmfn)(ARGS...), ARGS... data) : fun(std::bind( pmfn, ptr, data...)) {} derived_functor(TARGET& ref, RESULT (TARGET::*pmfn)(ARGS...), ARGS... data) : fun(std::bind(pmfn, ref, data... )) {} virtual void operator()() override { fun(); } private: std::function< void() > fun; }; template<typename T, typename R, typename... ARGS> inline // helper to deduce the types derived_functor<T,R,ARGS...> make_fun(T* p, R(T::*pmf)(ARGS...), ARGS... data) { return derived_functor<T,R,ARGS...>(p, pmf, data... ); } template<typename T, typename R, typename... ARGS> inline // helper to deduce the types derived_functor<T,R,ARGS...> make_fun(T& r, R(T::*pmf)(ARGS...), ARGS... data) { return derived_functor<T,R,ARGS...>( r, pmf, data...); } int main() { struct test { int foo(int, char) { std::cout << "int test::foo(int,char)" << std::endl; return 9; } void bar(long, double, test) { std::cout << "void test::bar(long,double,test)" << std::endl; } } test_it, another ; auto f1 = make_fun(&test_it, &test::foo, 7, 'a'); auto f2 = make_fun(test_it, &test::bar, 7L, 0.0, another); std::vector<std::reference_wrapper<base_functor>> functors = { f1, f2 }; for(auto& fn : functors) fn(); }
run
|
edit
|
history
|
help
0
vem de livezada
hey
Coin changes
Float
DFS
Finding Ocean
Test 20(2020)
Hello World
0-1 Knapsack
Christopher-Stellar