Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can You Use a Lambda In A Class' Initialization List?

Tags:

c++

c++11

lambda

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?

like image 811
John Dibling Avatar asked Jun 14 '12 16:06

John Dibling


Video Answer


1 Answers

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!
{
}
like image 82
stijn Avatar answered Oct 25 '22 12:10

stijn