C ++ lambda return type

I am writing a template function that takes a function object (now, lambda) as a parameter, with the lambda data type as the template parameter and returns the same type that the lambda returns. Like this:

template<typename TFunctor, typename TReturn>
TReturn MyFunc(TFunctor &Func, TReturn) //The second arg is just to keep the template spec happy
{
    return Func();
}

And the consumption code will look like this:

int n = MyFunc([](){return 17;}, int());

I don't like the ugly way of specifying the return data type. Is there a built-in typedef in the compiler-generated lambda class that will give me its return type? So MyFunc may look anyway:

template<typename TFunctor>
TFunctor::return_type MyFunc(TFunctor &Func)
{ //...

I want it to return the same type as lambda, without explicitly specifying that type.

EDIT: At the moment, all the lambdas I am involved with are indisputable. Capturing a variable also does the trick.

+4
1

, , -, . , ( () ), , .

++ 11 decltype, , , , ( Func):

template<typename TFunctor>
auto MyFunc(TFunctor &Func) -> decltype(Func(/* some arguments */))
{ ... }

, , , ( , ), :

template<typename TFunctor>
auto MyFunc(TFunctor &Func) -> decltype(Func())
{ 
    return Func();
}

++ 14

template<typename TFunctor>
auto MyFunc(TFunctor &Func)
{ 
    return Func();
}

, ++ 03 ; :

template<typename TReturn, typename TFunctor>
TReturn MyFunc(TFunctor &Func)
{
    return Func();
}

int n = MyFunc<int>(someFunctorReturningAnInt);
+4

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


All Articles