开发者

Scope in a lambda expression

#include "stdafx.h"
#include <iostream>
using namespace std;

template<class Type>
struct X
{
    void run()const
    {//Why on earth this doesn't work?
        [&]()
        {
            Type::alloc();
        };
    }
    void run_1()const
    {//if this does
        Type::alloc();
    }
};

struct T
{

    static void alloc()
    {}
};


int _tmain(int argc,开发者_StackOverflow社区 _TCHAR* argv[])
{
    X<T> x;
    x.run_1();
    return 0;
}

AFAIC lambda is a unnamed fnc, so if that's true why run doesn't compile and run_1 does?

Using VS2010 sp beta1.


You'll have to pass it in to the lambda:

    void run()const
    {//Why on earth this doesn't work?
        auto alloc = Type::alloc;
        [&]()
        {
            alloc();
        };
    }


I have to admit I am not quite sure, but I think is only a VS 2010 limitation and it should compile fine in C++0x (cf. templates, typename, lambda -> dependent names not dependent?). I think the mechanics of what you see are like following:

When defining template, types defined by template parameters are not "fully fledged" typenames in some aspects. One example demonstrating this is that while someone might expect X<Foo>::Type (with X from your example) to return Foo, it does not.


You have to call the lambda. It is a functor so you need a () at the end of it to effectively call the lambda.

/* Code does NOT answer question above...
void run()const
    {//Why on earth this doesn't work?
        [&]()
        {
            Type::alloc();
        }(); //very important parenthesis if you wish to call the lambda
    }*/

I seem to have misread the question. Sorry.


But there is already a similar post on SO Template type is not "seen" by the compiler inside a lambda

And here is another link that refers to the same problem, with a quote from the standard about this. templates, typename, lambda -> dependent names not dependent?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜