gpt4 book ai didi

c++ - lambda 表达式中的作用域

转载 作者:太空狗 更新时间:2023-10-29 20:47:49 25 4
gpt4 key购买 nike

#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 是一个未命名的 fnc,所以如果这是真的,为什么 run 不能编译而 run_1 可以?
使用 VS2010 sp beta1。

最佳答案

你必须将它传递给 lambda:

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

关于c++ - lambda 表达式中的作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4711935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com