9

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"?

Community
  • 1
  • 1
Praxeolitic
  • 22,455
  • 16
  • 75
  • 126
  • How to default construct a type that is unspecified? And why you would want to do this when you can assign a lambda to a `std::function`? – 101010 Oct 23 '15 at 20:26
  • 2
    @101010 The type is `decltype(t)` in the example. A lambda is preferable to `std::function` because `std::function` introduces unneeded indirection in this case (there's no question about what function we want and we're not going to change our mind later) plus the lambda definition can be placed right where it's used. – Praxeolitic Oct 23 '15 at 20:28

1 Answers1

4

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).

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • Have there been accepted proposals from folks who are not involved with the committee or well known C++ gurus? – Praxeolitic Oct 23 '15 at 20:45
  • @Praxeolitic, to have any slight change of acceptance it has to be accompanied by implementation. – SergeyA Oct 23 '15 at 20:59
  • 1
    @SergeyA That's obviously false if the proposal is well structured and has both a persuasive motivation section and sound wording. Existing implementation raises the change of acceptance to some extent but isn't necessary (and certainly doesn't compensate for more important traits of your paper). – Columbo Oct 23 '15 at 22:18