如果我能做到以下几点,那就太好了:
template <class RT, class... PT>
class Event
{
...
void operator()(PT... args)
{
std::for_each(
l.begin(), l.end(), [args...](Handler *p) { (*p)(args...); }
);
}
...
};
很遗憾,我无法使用g++ 4.7.2 (-std=c++0x)编译它:
evtempl.hh:在成员函数'void elt :: Event :: operator()(PT ...)'中: evtempl.hh:75:54: 错误:在“...”标记之前需要“,” evtempl.hh:75:54: 错误:在“...”标记之前需要标识符 evtempl.hh:75:57: 错误:未展开参数包: evtempl.hh:75:57: 注意:'args' evtempl.hh:在lambda函数中: evtempl.hh:76:26: 错误:扩展模式“args”不包含任何参数包 evtempl.hh:在实例化'void elt :: Event :: operator()(PT ...)[with RT = void; PT = {int}]'时: testevtempl.cc:28:9: 在此需要 evtempl.hh:74:9: 错误:使用无效字段'elt :: Event :: operator()(PT ...)::::Handler*)>> :: __args' evtempl.hh:在实例化'void elt :: Event :: operator()(PT ...)[with RT = void; PT = {int,const char *}]'时: testevtempl.cc:29:20: 在此需要 evtempl.hh:74:9: 错误:使用无效字段'elt :: Event :: operator()(PT ...)::::Handler*)>> :: __args'
相反,我必须将该lambda更改为旧的单调语法:
for (itr = l.begin(); itr != l.end(); ++itr)
(*(*itr))(args...);
这个程序编译并且运行正常。
我想知道为什么lambda语法不起作用。
- 我做错了什么或者错过了什么?
- c++11标准禁止这种语法吗?
- 还是这种语法在标准中允许,但是当前编译器有问题?
我尝试过
[=](Handler *p) { (*p)(args...); }
如果您执行以下操作,它将给出与该错误相同的错误:
[args](Handler *p) { (*p)(args...); }
投诉参数包没有展开
[=]
替代吗? - Kerrek SBauto foo = [=](Handler *p) { (*p)(args...); };
部分拆开来看,你会得到两个错误提示:“1)参数包未展开”和“2)展开模式 'args' 不包含参数包”。我怀疑这是 GCC 的一个 bug,因为它既在抱怨 args 不是一个参数包,又在说 args 必须是一个参数包。 - Dave S