Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ generic lambdas: pattern type deduction

In C++20, under the proposal Familiar template syntax for generic lambdas, the following code correctly deduces type T:

auto lamTest = []<typename T>(std::initializer_list<T> const & l)
{
    std::vector<T> v{ l };
    for (auto && e : v)
        std::cout << e << " ";
};
lamTest( { 1,2,3 } );

Is it possible to do this kind of pattern deduction in C++17 (or 14)?

Note: I am asking specifically about lambda expressions.

like image 567
ThomasMcLeod Avatar asked Jun 20 '26 20:06

ThomasMcLeod


1 Answers

That's standard function template deduction. It's no different from this:

template<typename T>
auto lamTest(std::initializer_list<T> const & l)
{
    std::vector<T> v{ l };
    for (auto && e : v)
        std::cout << e << " ";
};

Which (std::initializer_list aside) is regular C++98 code.

The only new thing C++20 is adding is the ability to write lambdas with an explicit template parameter list, rather than (or in addition to) C++14's auto. In every other way, it behaves just like any other template function.

like image 121
Nicol Bolas Avatar answered Jun 23 '26 18:06

Nicol Bolas