c++ - 如何从模板结构创建二维数组

标签 c++ templates template-specialization

我已经就下面的代码提出了几个问题,并得到了很多帮助……我对 C++ 还很陌生,只是在玩弄我在此处实际找到的这段代码。我想创建一个二维数组,然后可用于调用采用 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;
}

最佳答案

这可能会让你更接近:

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

};

这个程序还有很多其他的问题,但是...

关于c++ - 如何从模板结构创建二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32215300/

相关文章:

c++ - 如何知道链自定义operator<<调用的次数?

c++ - 返回一个迭代器

c++ - 是否可以使用模板来识别两种不同的类型?

c++ - 模板特化/初始化和命名空间?

c++ - 如何简化 std::variant 类类型

c++ - 回文函数(字符串、堆栈、队列)

c++ - std::dynamic_pointer_cast 的别名

C++ 模板类给出没有明显错误的语法错误

C++ 模板 : Partial template Function Specialization in template class

c++ - 类模板特化的运算符重载