[英]Parameter pack expansion with lambda
I am trying to instantiate a function table (to emulate switch<\/code> )
我正在尝试实例化一个函数表(模拟
switch<\/code> )
template<size_t ... N>
int f(std::index_sequence<N...>, int k)
{
static auto f_table = { []() { return N; }... };
auto f = f_table.begin() + k;
assert((*f)() == k);
return (*f)();
}
It was a bug that GCC doesn't expand template parameter pack that appears in a lambda-expression , which was fixed in GCC 8 eventually. GCC 没有扩展出现在 lambda-expression 中的模板参数包是一个错误,该错误最终在 GCC 8 中得到修复。
The other issue with the code as also mentioned in the comments is that every lambda in the list { []() { return N; }... }
注释中还提到的代码的另一个问题是列表中的每个 lambda { []() { return N; }... }
{ []() { return N; }... }
has its own distinct type, so one has to convert them into function pointers with +
operator first: { []() { return N; }... }
有自己独特的类型,所以必须先用+
运算符将它们转换为函数指针:
#include <utility>
#include <cassert>
template<std::size_t ... N>
int f(std::index_sequence<N...>, std::size_t k) {
static auto f_table = { +[]() { return N; }... };
auto f = f_table.begin() + k;
assert((*f)() == k);
return (*f)();
}
int main() {
f(std::make_index_sequence<3>{}, 2);
}
Demo: https://gcc.godbolt.org/z/jWrfn7d6W演示: https ://gcc.godbolt.org/z/jWrfn7d6W
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.