Search code examples
c++11lambdatype-deduction

Can I deduce the return type of a lambda without actually calling it?


It might seem obvious to some, but I was still wondering: is there no way to make the compiler deduce the lambda return type without actually calling it?

Of course you can auto retval = myLambda();, however I want sth like:

T_MY_LAMBDA_RETVAL retval;
...
retval = myLambda();

Why would I want that? Simple:

try {
    auto retval = myLambda();
catch (exception e) {
    ...
}

// retval is undefined but I wonna have it!!! :)

Solution

  • typedef typename std::result_of<decltype(lambda)()>::type return_type;
    

    deduces the return type of invoking lambda with 0 arguments.

    As would:

    typedef decltype( lambda() ) return_type;
    

    Be careful about possible rvalue references.