【问题标题】:Variadic templates for lambda expressionslambda 表达式的可变参数模板
【发布时间】:2010-07-31 11:14:24
【问题描述】:

使用 g++ 的正确方法是什么:

template < typename F >
void g (F f);

template < typename ... A >
void h (A ... a);

template < typename ... A >
void f (A ... a) {
  g ([&a] () { h (a...); }); // g++-4.6: error: parameter packs not expanded with »...«
}

【问题讨论】:

    标签: c++ templates g++ c++11


    【解决方案1】:

    我认为您还需要在捕获列表中扩展包a,如下所示:

    template < typename ... A >
    void f (A ... a) {
      g ([&, a...] () { h (a...); }); 
    }
    

    这是来自 C++0x 最终委员会草案,第 5.1.2.23 节的相关文本:

    捕获后跟省略号是 包扩展(14.5.3)。 [ 例子:

    template<class... Args> void f(Args... args) {
        auto lm = [&, args...] { return g(args...); }; lm();
    }
    

    —结束示例]

    【讨论】:

    • 谢谢。 g++-4.6 尚不接受草案中的此语法:test01.cc:2:23: Fehler: expected »,« before »...« token
    • 我通过创建一个元组,将它传递给 lambda 函数并在那里解包来解决它。
    • 看起来 g++-4.8 仍然不接受这种语法,但 ICC 13.0.1 接受:bit.ly/14auYGy
    【解决方案2】:
    #include <functional>
    template < typename ... A >
    void f (A ... a) {
      g (std::bind(h, a...));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-09
      • 2015-05-12
      • 2022-09-23
      • 2011-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多