Search code examples
c++typenamec++20generic-lambda

Why are C++20 template lambdas using typename keyword?


I understand the consistency argument, but most of the parameters for templates are types so I feel that since lambdas are meant to be concise way of defining a struct it probably should have been defaulted to typename/class(you would still need to write int/size_t/short).

If somebody is not familiar with changes to lambdas in C++20 here is the example:

[]<typename T>(const std::vector<T>& v)
{
    for(const auto& x : v) { std::cout << x; }
};

and my question is why not:

[]<T>(const std::vector<T>& v)
{
    for(const auto& x : v) { std::cout << x; }
};

Solution

  • The problem is that this already has a meaning:

    template <T> void foo();
    

    It's a function template with one template parameter that is a non-type template parameter whose type is T, and that template parameter has no name.

    It would be pretty confusing if the same syntax meant very different things depending on if you're introducing a function template or a generic lambda -- which is to say, two very similar contexts serving similar purposes!

    Plus then... what would you do if you actually want a non-type template parameter? Just can't have one?