Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to use lambda in initialization list of template in C++

I have a class with a std::function constructor parameter.

class ClazzA{
public:
    ClazzA(function<void()> foo){}
    ClazzA(){
        ClazzA([](){});
    }
};

If I have an instance of this class as a member of another, I have to call constructor in initializer list. I can pass a lambda as an argument, and it is automatically converted:

class ClazzB{
public:
    ClazzA a;
    ClazzB() :
      // works fine:
      a([](){}){}
};

But if ClazzB is a template, lambda doesn't work:

template<typename T> class ClazzC{
public:
    ClazzA a;
    //works fine:
    ClazzC(function<void()> foo) : a(foo){}
    //doesn't work:
    ClazzC() :
      //syntax error : ')'
      a([](){})
      //syntax error : '{'
      //unexpected token(s) preceding '{'; skipping apparent function body
      {}
};

The compiler is MSVC++ 2010. I don't understand what I am doing wrong or why this syntax is not supported.

At first ClazzA was a template too, and function was a bit more complex, so I thought it was the problem with templated lambda or something. But after I removed all that code the problem remains.

UPD: Tried to compile in MinGW G++, it works. Looks like a Visual Studio issue.

like image 654
aimozg Avatar asked Jul 08 '11 12:07

aimozg


1 Answers

This is a MSVS C++0x implementation problem (see comments under question). Problem solved.

like image 104
aimozg Avatar answered Oct 02 '22 14:10

aimozg