【发布时间】:2015-08-25 22:43:09
【问题描述】:
我已经对下面的代码提出了几个问题,并得到了很多帮助……我对 C++ 还很陌生,只是在玩我实际上在这里找到的这段代码。我想创建一个 2d 数组,然后可以使用它来调用带有 2 个模板参数的模板函数。下面的代码和问题/cmets。我现在宁愿把它作为一个纯数组(不是 std::array),这样我就可以理解发生了什么。
class Test
{
public:
template<int N>
bool foo(double x, double y) { assert(false); }
template<bool B, int N>
double foo2(double x, double y) { assert(false); }
template<int N, int... Ns>
struct fn_table : fn_table < N - 1, N - 1, Ns... > {};
template<int... Ns>
struct fn_table < 0, Ns... >
{
//this expands to foo<0>,foo<1>...foo<Ns>,correct?
static constexpr bool(*fns[])(double, double) = {foo<Ns>...};
//how to make this part work for 2d array to include bool from foo2?
// Compiler gives: "parameter packs not expanded with ..."
static constexpr bool(*fns2[][Ns])(double, double) = {foo2<Ns, Ns>...};
//instead of [][Ns] and <Ns,Ns> can we explicity only create 2 rows for bool?
};
};
template<> bool Test::foo<5>(double x, double) { return false; }
//will below work? will false be converted to match 0 from call in main?
template<> double Test::foo2<false, 1>(double x, double y) { return x; }
template<int... Ns>
constexpr bool(*Test::fn_table<0, Ns...>::fns[sizeof...(Ns)])(double, double);
//how to define for 2d fns2?
template<int... Ns>
constexpr bool(*Test::fn_table<0, Ns...>::fns2[][sizeof...(Ns)])(double, double);
int main(int argc, char* argv[])
{
int val = atoi(argv[0]);
int val2 = atoi(argv[1]);
Test::fn_table<5> table;
bool b = table::fns[val];
double d = table::fns2[0, val];
double d = table::fns2[false, val];//does false convert to 0?
return 0;
}
【问题讨论】:
标签: c++ templates template-specialization