Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason lambdas with an empty capture-list can't be default constructed?

Tags:

c++

c++11

lambda

C++'s lambdas would be convenient to use in templates that need function objects but alas, they cannot be default constructed.

As discussed in this question, this makes sense for lambdas that have a non-empty capture-list.

Instantiating C++ lambda by its type

Kerrek explains:

The code doesn't make sense. Imagine you have a capturing lambda like this:

{
    int n = 0;
    auto t = [&n](int a) -> int { return n += a; };
}

What could it possibly mean to default-construct an object of type decltype(t)?

What about lambdas with an empty capture-list? Is there a reason those also don't make sense to default construct? Is there anything more to it than "the standard says so"?

like image 983
Praxeolitic Avatar asked Oct 23 '15 20:10

Praxeolitic


1 Answers

In general, lambdas where specified as little as possible to solve specific use cases.

Other possibly useful things, like "a lambda that only copies trivially copyable data must be trivially copyable" was also omitted. (The standard does not specify if a lambda is trivially copyable or not)

The upside is that it makes lambda an easier to implement feature, which is important. The downside is that this rules out certain uses that are not in the "intended" set.

If you think that "a capture free lambda must have a zero-argument constructor" is an important thing, propose it. But this takes one use of lambdas (easy local capture and creation of function objects) and morphs it into something else (easy creation of stateless function objects whose types can be passed around).

like image 103
Yakk - Adam Nevraumont Avatar answered Sep 22 '22 16:09

Yakk - Adam Nevraumont