如何从模板化结构创建2d数组

时间:2015-08-25 22:43:09

标签: c++ templates template-specialization

我已经在下面的代码中提出了几个问题并得到了很多帮助......我对C ++很新,只是玩这个我实际上在这里找到的代码。我想创建一个2d数组,然后可以使用2个模板参数来调用模板函数。下面是代码和问题/注释。我现在宁愿把它留作纯数组(不是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;
}

1 个答案:

答案 0 :(得分:0)

这可能会让你更接近:

template<int... Ns>
struct fn_table < 0, Ns... >
{
    static constexpr double(*fns2[2][sizeof...(Ns)])(double, double) =
    { { &foo2<false, Ns>... }, { &foo2<true, Ns>... } }; 

};

该计划还有许多其他问题,但是......