Lambda捕获是否支持可变参数模板参数 [英] Does lambda capture support variadic template arguments

查看:132
本文介绍了Lambda捕获是否支持可变参数模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我可以执行以下操作,那就太好了:

It would be nice if I could do the following:

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 ):

Unfortunately I couldn't make it compile with g++ 4.7.2 (-std=c++0x):


evtempl.hh:在成员函数'void elt :: Event :: operator()(PT ...)':
evtempl.hh:75:54:错误:预期','在'...'令牌之前
evtempl.hh:75:54:错误:预期标识符在'...'令牌$ b之前$ b 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 =虚空PT = {int,const char *}]':
testevtempl.cc:29:20:此处需要
evtempl.hh:74:9:错误:使用无效字段'elt :: Event: :operator()(PT ...):::: Handler *)> :: __ args'

evtempl.hh: In member function 'void elt::Event::operator()(PT ...)': evtempl.hh:75:54: error: expected ',' before '...' token evtempl.hh:75:54: error: expected identifier before '...' token evtempl.hh:75:57: error: parameter packs not expanded with '...': evtempl.hh:75:57: note: 'args' evtempl.hh: In lambda function: evtempl.hh:76:26: error: expansion pattern 'args' contains no argument packs evtempl.hh: In instantiation of 'void elt::Event::operator()(PT ...) [with RT = void; PT = {int}]': testevtempl.cc:28:9: required from here evtempl.hh:74:9: error: using invalid field 'elt::Event::operator()(PT ...)::::Handler*)>::__args' evtempl.hh: In instantiation of 'void elt::Event::operator()(PT ...) [with RT = void; PT = {int, const char*}]': testevtempl.cc:29:20: required from here evtempl.hh:74:9: error: using invalid field 'elt::Event::operator()(PT ...)::::Handler*)>::__args'

相反,我必须将该lambda更改为旧的普通语法:

instead, I have to change that lambda to the old, mundane syntax:

for (itr = l.begin(); itr != l.end(); ++itr)
     (*(*itr))(args...);

这个可以编译并正常工作。

This one compiles and works fine.

我想知道为什么lambda语法不起作用。

I wonder why the lambda syntax doesn't work.


  1. 我做错了什么吗?

  2. c ++ 11标准中是否禁止了这种事情?

  3. 还是标准允许的,但这是当前编译器的
    a问题?

我尝试了

[=](Handler *p) { (*p)(args...); }

它会产生与您相同的错误:

it gives the same error as if you did:

[args](Handler *p) { (*p)(args...); }

抱怨参数包没有扩展

推荐答案

这是gcc中的错误。请参见 [c ++ 0x] lambda和可变参数模板不能一起使用 [C ++ 11]包扩展在lambda表达式中失败

It's a bug in gcc. See [c++0x]lambdas and variadic templates don't work together or perhaps [C++11] Pack expansion fails in lambda expressions.

这篇关于Lambda捕获是否支持可变参数模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆