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 是一个未命名的 fnc,所以如果这是真的,为什么 run 不能编译而 run_1 可以编译?
使用VS2010 sp beta1。
#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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须将其传递给 lambda:
You'll have to pass it in to the lambda:
我必须承认我不太确定,但我认为这只是 VS 2010 的限制,它应该可以在 C++0x 中正常编译(参见 模板、类型名称、lambda -> 依赖名称不依赖?)。我认为您所看到的机制如下:
定义模板时,模板参数定义的类型在某些方面不是“完全成熟的”类型名。证明这一点的一个例子是,虽然有人可能期望
X::Type
(在示例中使用 X)返回 Foo,但事实并非如此。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.你必须调用 lambda。它是一个函子,所以你需要在它的末尾有一个 () 来有效地调用 lambda。我似乎误读了这个问题。对不起。
但已经有一个类似的帖子关于SO 模板编译器在 lambda 内“看不到”类型
这里是另一个引用相同问题的链接,并引用了有关此问题的标准。
模板、类型名称、lambda ->依赖名称不依赖?
You have to call the lambda. It is a functor so you need a () at the end of it to effectively 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?