【发布时间】:2017-12-15 15:43:14
【问题描述】:
下面的小程序可以编译和运行,它允许将unsigned 类型的运行时变量index 与一组具有J 类型unsigned 的模板参数的模板函数桥接。
如果需要进一步澄清,请在this question 中进行更好的解释。
我编写的辅助函数使用模板模板参数,从原始函数中推断出尽可能多的信息。问题是我找不到更好的方法来定义模板模板参数FunWrap,而不是创建2个包装器wrap_foo和wrap_zoo,而我希望直接用作模板模板参数foo和zoo。有没有办法做到这一点?
#include <iostream>
#include <utility>
#include <array>
using namespace std;
// boiler plate stuff
template <template <unsigned J> typename FunWrap, unsigned... Is>
decltype(auto) get_fun_ptr_aux(std::integer_sequence<unsigned, Is...>, unsigned i)
{
typedef decltype(&FunWrap<1>::run) FunPtr;
constexpr static std::array<FunPtr, sizeof...(Is)> fun_ptrs = { &FunWrap<Is>::run... };
return fun_ptrs[i];
}
template <template <unsigned J> typename FunWrap, unsigned N>
decltype(auto) get_fun_ptr(unsigned i)
{
return get_fun_ptr_aux<FunWrap>(std::make_integer_sequence<unsigned, N>{}, i);
}
// template functions to be bridged with runtime arguments
// two functions with same template arguments but different signature
template <unsigned J>
void foo() { cout << J << "\n"; }
template <unsigned J>
double zoo(double x) { return x + J; }
// 1 wrapper per each function
template <unsigned J>
struct wrap_foo {
static void *run() { foo<J>(); } // same signature as foo
};
template <unsigned J>
struct wrap_zoo {
static double run(double x) { return zoo<J>(x); } // same signature as zoo
};
int main()
{
unsigned index = 5;
(*get_fun_ptr<wrap_foo,10>(index))();
cout << (*get_fun_ptr<wrap_zoo,10>(index))(3.5) << "\n";
return 0;
}
【问题讨论】:
标签: templates c++14 template-templates