Capturing non-type template parameter in lambda expression

Viewed 111

Why it's forbidden to capture non-type template parameters in the lambda capture list?

The following code fails to compile on both GCC and clang:

template<int x>
auto foo()
{
    return [x]{return x;};
}

with an error message capture of non-variable 'x' on GCC and 'x' in capture list does not name a variable on clang.

... however, the following code compiles fine:

template<int x>
auto bar()
{
    return [y = x]{return y;};
}
1 Answers

You cannot capture them because you don't need to. Template parameters of the enclosing function/class of a lambda are accessible to the lambda. Just like template parameters of a class template are accessible to any member function of that class template.

Related