Convert overloaded function to template function

I have several overloaded functions like

int a(int) {/*...*/} float a(float) {/*...*/} /* ... */ int b(int) {/*...*/} float b(float) {/*...*/} /* ... */ 

My goal is to wrap these functions in a functor object:

 template <typename T> struct func_a { auto T operator()(T t) -> decltype(a(t)) {return a(t);} }; 

Is there a way to determine the structure of the template described above over any other template by taking an overloaded function as an argument? Something like that:

 template </* pointer to an overloaded function f */> struct create_functor { template <typename T> struct func { auto operator()() -> decltype(f(t)) {return f(t);} } }; 

Therefore, I can generate the structure at compile time, as in:

 typedef create_functor<a>::func<int> func_a_int; typedef create_functor<a>::func<float> func_a_float; typedef create_functor<b>::func<int> func_a_int; typedef create_functor<b>::func<float> func_a_float; 
+4
c ++ c ++ 11 functor
source share
2 answers

You can define an overload set for each of your functions, for example:

 int a(int i) {return 2*i;} float a(float d) {return 3*d;} #define overload_set(f, f_set) \ struct f_set { \ template <typename... Args> \ auto operator()(Args&&... args) \ -> decltype(f(std::forward<Args>(args)...)) \ { \ return f(std::forward<Args>(args)...); \ } \ } overload_set(a, a_set); // more overload_set here... 

Using an overload set instead of a function pointer makes the create_functor implementation simple:

 template <typename OverloadSet> struct create_functor { template <typename... Args> struct func { auto operator()(Args... args) -> decltype(OverloadSet{}(args...)) { return OverloadSet{}(args...); } }; }; create_functor<a_set>::func<int> func_a_int; // Note: no need for typedef here create_functor<a_set>::func<float> func_a_float; int main() { std::cout << func_a_int(2) << std::endl; std::cout << func_a_float(3.) << std::endl; } 
+3
source share

As long as the signatures of different overloads are the same, as in your question, this can be done using the value of the function pointer as a template parameter:

 template<typename T> struct create_functor { template<T(*fct)(T)> struct functor { T operator()(T n) { return fct(n); } }; }; create_functor<int>::functor<a> func_a_int; create_functor<float>::functor<a> func_a_float; std::cout << func_a_int(42) << func_a_float(3.14f) << std::endl; 
+1
source share

All Articles