using namespace std; template struct X { void run()const {//Why...">

Scope in 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, _TCHAR* argv[])
{
    X<T> x;
    x.run_1();
    return 0;
}

AFAIC lambda is an unnamed fnc, so if it's true, why does not run run and run_1 do?
Using VS2010 sp beta1.

+3
source share
3 answers

You need to pass it to lambda:

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

I have to admit that I'm not quite sure, but I think this is only a limitation of VS 2010, and it should compile in C ++ 0x (cf. templates, typename, lambda - → dependent names are independent of ; I think the mechanics of what you see is as follows:

, , "" . , , , , - X<Foo>::Type ( X ), Foo, .

+2

You need to call lambda. This is a functor, so you need () at the end of it to effectively call 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
    }*/

It seems I misunderstood the question. Unfortunately.


But there already exists a similar entry on SO. The type of the template is not displayed and the "compiler inside lambda

And here is another link that refers to the same problem, with a quote from the standard about it. templates, typename, lambda - → dependent names are independent?

+1
source

Source: https://habr.com/ru/post/1785876/


All Articles