lambda 表达式的可变参数模板

2022-01-23 00:00:00 templates g++ c++ c++11

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

What's the correct way to do this with 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 ?...?
}

推荐答案

我想你也需要在捕获列表中展开pack a,像这样:

I think you need to expand the pack a in the capture list as well, like this:

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

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

Here is the relevant text from the C++0x Final Committee Draft, section 5.1.2.23:

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

A capture followed by an ellipsis is a pack expansion (14.5.3). [ Example:

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

―结束示例]

相关文章