How to establish trailing return type of lambda function that use template functions?

89 Views Asked by At

How can I make trailing return type deduction in the following code snippet that uses a template function? Code works well as it is now, but I need to know if I can also add trailing return for the lambda function..

template<class T>
T print(T a){
    cout << a;
    return a;
};

int main()
{
    auto print_int = [](int a)/*->How?*/{
        return print<int>(a);
    };
    print_int(4);
}
2

There are 2 best solutions below

0
NutCracker On

You can do the following:

auto print_int = [](int a) -> decltype(print<int>(a)) {
    return print<int>(a);
};
0
cigien On

You can simply do:

auto print_int = [](int a) -> auto {
    return print<int>(a);
};

or

auto print_int = [](int a) -> decltype(auto) {
    return print<int>(a);
};