Deriving an Autonomous Function Return Type

I am trying to find the return type of a non-member function. At first, I thought std::result_of doing this work, but it seems that the latter only works for called objects. In particular, std::result_of<decltype(f)>::type does not work . I finally managed to find a code that works

 #include <iostream> #include <typeinfo> void f(int); // we deduce the returning type of this function template<typename Ret, typename... Args> struct Helper { using type = Ret; }; template<typename Ret, typename... Args> Helper<Ret, Args...> invoke(Ret(*fp)(Args...)) { return {}; } template<typename Ret, typename... Args> using Return_Type = typename Helper<Ret, Args...>::type; int main() { std::cout << typeid(decltype(invoke(f))::type).name() << std::endl; // fine } 

I am using an additional function here, the invoke pattern, which takes a pointer to the function that I want to infer the return type and returns a helper structure from which I read the actual return type.

The code seems a bit confusing as it includes a call function (although the actual evaluation is not performed). Is there any other alternative simpler / clearer / shorter way to do this?

0
source share
3 answers

Advising my own old blog post about this, I discovered:

 template< class Func > struct ResultOf { typedef typename std::function< typename std::remove_pointer<Func>::type >::result_type T; }; 
+6
source
 template<typename> struct return_t_impl; template<typename Ret, typename... Args> struct return_t_impl <Ret(Args...)> { using type = Ret; }; template<typename Ret, typename... Args> struct return_t_impl<Ret(*)(Args...)> : return_t_impl<Ret(Args...)> {}; template<typename T> using return_t = typename return_t_impl<T>::type; 

And use it like:

 using type = return_t<decltype(f)>; //type is void 
+3
source
 template<class F> using return_t = typename std::function<std::remove_pointer_t<std::decay_t<F>>>::result_type; 
+2
source

Source: https://habr.com/ru/post/988462/


All Articles