【发布时间】:2014-09-04 03:47:32
【问题描述】:
我想“生成”一个函数指针跳转表。指向的函数被模板化为两种类型。应该为两个类型列表中的每个可能对实例化一个不同的函数。理想情况下,我们可以有类似的东西:
#include <tuple>
template <typename X, typename Y>
void foo()
{}
template <typename... Xs, typename... Ys>
void bar(const std::tuple<Xs...>&, const std::tuple<Ys...>&)
{
using fun_ptr_type = void (*) (void);
static constexpr fun_ptr_type jump_table[sizeof...(Xs) * sizeof...(Ys)]
= {&foo<Xs, Ys>...};
}
int main ()
{
using tuple0 = std::tuple<int, char, double>;
using tuple1 = std::tuple<float, unsigned long>;
bar(tuple0{}, tuple1{});
}
正如预期的那样,当元组长度不同时它会失败:
foo.cc:15:20: error: pack expansion contains parameter packs 'Xs' and 'Ys' that have different lengths (3 vs. 2)
= {&foo<Xs, Ys>...};
~~ ~~ ^
foo.cc:23:3: note: in instantiation of function template specialization 'bar<int, char, double, float, unsigned long>' requested here
bar(tuple0{}, tuple1{});
^
1 error generated.
为了实现这种功能,我已经尝试了indirection(第一个跳转表,其中包含指向另一个跳转表的函数的指针),但我觉得它很笨拙。
所以,我的问题是:有解决方法吗?
【问题讨论】:
标签: c++ c++11 c++14 variadic-templates