G++ 4.6.3 Lambda BUG ?

gbb21 2012-08-02 09:43:05
Following Code will fail to compile

1 #include <iostream>
2 #include <vector>
3
4 using namespace std;
5
6 template <typename T>
7 struct MyClass
8 {
9 int func()
10 {
11 return 0;
12 }
13
14 void test()
15 {
16 [=] {
17 func(); // It will be fine if I change it into this->func();
18 }();
19 }
20 };
21
22 int main()
23 {
24 MyClass<int> c;
25 c.test();
26 return 3;
27 }

18:35:Dashboard$g++ -std=c++0x a.cpp
a.cpp: In lambda function:
a.cpp:16:5: instantiated from ‘MyClass<T>::test() [with T = int]::<lambda()>’
a.cpp:16:3: instantiated from ‘void MyClass<T>::test() [with T = int]’
a.cpp:25:9: instantiated from here
a.cpp:17:4: error: ‘func’ was not declared in this scope

Is this a bug or standard behavior ? Thx.
...全文
143 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
酱油党 2012-08-02
  • 打赏
  • 举报
回复
a.cpp:17:4: error: ‘func’ was not declared in this scope
另外编译器告诉你在第十四行func函数没有在这里被声明
pengzhixi 2012-08-02
  • 打赏
  • 举报
回复
具体可以看模板关于Nondepend name查找规则。我估计你lambd表达式中的func这个nondepend name会到全局namespace中去查找了。你可以定义一个全局的func()函数实验下。
gbb21 2012-08-02
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

这个是标准行为。具体来说是由于模板造成的。你可以用this->func();也可以用MyClass::func();
[/Quote]

Thanks!
>> 具体来说是由于模板造成的
I understand this , but would you please point me to the C++ spec section that describe that behavior ?
pengzhixi 2012-08-02
  • 打赏
  • 举报
回复
这个是标准行为。具体来说是由于模板造成的。你可以用this->func();也可以用MyClass::func();
gbb21 2012-08-02
  • 打赏
  • 举报
回复
这个是相关介绍:http://eli.thegreenplace.net/2012/02/06/dependent-name-lookup-for-c-templates/
gbb21 2012-08-02
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]

具体可以看模板关于Nondepend name查找规则。我估计你lambd表达式中的func这个nondepend name会到全局namespace中去查找了。你可以定义一个全局的func()函数实验下。
[/Quote]

果然,编译器认为func()是一个nondependent name了, 加入this-> 或者 MyClass<T>::后编译器才认识到其是一个dependent name。谢谢。

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧