14

I am trying to use a C++11 Lambda to initialize a const member variable of a class.

A much simplified example:

class Foo
{
public:
    const int n_;
    Foo();
};

Foo::Foo()
:   n_( []() -> int { return 42; } )
{
}

int main()
{
    Foo f;
}

In MSVC10 this yields:

error C2440: 'initializing' : cannot convert from '`anonymous-namespace'::<lambda0>' to 'const int'

In IDEONE this yields:

prog.cpp: In constructor 'Foo::Foo()':
prog.cpp:9:34: error: invalid conversion from 'int (*)()' to 'int'

I'm starting to get the idea that I can't use lambdas in a class' initialization list.

Can I? If so, what's the proper syntax?

3 Answers 3

28

you are trying to convert from a lambda to int - you should call the lambda instead:

Foo::Foo()
:   n_( []() -> int { return 42; }() ) //note the () to call the lambda!
{
}
Sign up to request clarification or add additional context in comments.

Comments

7

Your variable is declared as int.

Do you want to invoke the lambda? This should work:

n_(([]() -> int { return 42; })())

Or did you want a variable of type std::function<>?

3 Comments

+1: Yes, I am trying to populate n_ by returning the value from the lambda.
@John See update. And I actually see how that can be useful with a more complex (multi-statement) lambda.
Exactly. In my actual use case, I am storing the size of a read-only file in bytes.
2

You're creating a lambda, this way as compiler states, you're trying to store the lambda itself in n_.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.