Get return value for template lambda parameter, ho

2019-05-10 18:54发布

问题:

This is my trick:

template<typename F, typename TArg>
auto get_return_value(F * f = NULL, TArg * arg = NULL)
     -> decltype((*f)(*arg));

Example of using:

template<typename F, typename T>
decltype(get_return_value<F,T>()) applyFtoT(F f, T t)
{
    return f(t);
}

In case F is lambda:

int b = applyFtoT([](int a){return a*2}, 10);
// b == 20

Function get_return_value looks ugly i think... How to simplify it?

回答1:

It seems like you could eliminate the need for get_return_value by changing the declaration of applyFtoT like so:

template<typename F, typename T>
auto applyFtoT(F f, T t) -> decltype(f(t))
{
   return f(t);
}