Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope in a lambda expression

Tags:

c++

c++11

lambda

#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 a unnamed fnc, so if that's true why run doesn't compile and run_1 does?
Using VS2010 sp beta1.

like image 551
There is nothing we can do Avatar asked Apr 14 '26 07:04

There is nothing we can do


1 Answers

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();
        };
    }
like image 162
Moo-Juice Avatar answered Apr 15 '26 19:04

Moo-Juice