The deduced return type when passing a function according to a template

My question is that the compiler infers the return type of the function based on the return type of the function passed in by the template.

Is there any way I can name

foo<bar>(7.3) 

instead

 foo<double, int, bar>(7.3) 

in this example:

 #include <cstdio> template <class T, class V, V (*func)(T)> V foo(T t) { return func(t); } int bar(double j) { return (int)(j + 1); } int main() { printf("%d\n", foo<double, int, bar>(7.3)); } 
+4
source share
1 answer

If you want to keep bar as a template argument, I'm afraid you can come close to this:

 #include <cstdio> template<typename T> struct traits { }; template<typename R, typename A> struct traits<R(A)> { typedef R ret_type; typedef A arg_type; }; template <typename F, F* func> typename traits<F>::ret_type foo(typename traits<F>::arg_type t) { return func(t); } int bar(double j) { return (int)(j + 1); } int main() { printf("%d\n", foo<decltype(bar), bar>(7.3)); } 

You can also define a macro if you want to avoid repeating the bar name:

 #define FXN_ARG(f) decltype(f), f int main() { printf("%d\n", foo<FXN_ARG(bar)>(7.3)); } 

Alternatively, you can let bar become an argument to a function, making your life easier:

 #include <cstdio> template<typename T> struct traits { }; template<typename R, typename A> struct traits<R(A)> { typedef R ret_type; typedef A arg_type; }; template<typename R, typename A> struct traits<R(*)(A)> { typedef R ret_type; typedef A arg_type; }; template <typename F> typename traits<F>::ret_type foo(F f, typename traits<F>::arg_type t) { return f(t); } int bar(double j) { return (int)(j + 1); } int main() { printf("%d\n", foo(bar, 7.3)); } 
+1
source

All Articles