C++ – Can You Use a Lambda In A Class’ Initialization List

cc++11lambda

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?

Best Answer

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!
{
}