Variadic templates for lambda expressions

2020-03-01 17:11发布

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 »...«
}

2条回答
家丑人穷心不美
2楼-- · 2020-03-01 17:40
#include <functional>
template < typename ... A >
void f (A ... a) {
  g (std::bind(h, a...));
}
查看更多
兄弟一词,经得起流年.
3楼-- · 2020-03-01 18:02

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...); }); 
}

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

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();
}

— end example ]

查看更多
登录 后发表回答