【问题标题】:how to create 2d array from templated struct如何从模板结构创建二维数组
【发布时间】: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


    【解决方案1】:

    这可能会让你更接近:

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

    };

    该程序还有许多其他问题...

    【讨论】:

    • 啊,我明白了..这是有道理的..还有哪些其他问题?在编译方面,如果引用 fns2 的语句被删除,它将编译。
    • 看起来可行。我想知道 bool/int 转换是否可行。
    猜你喜欢
    • 2017-03-08
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 2013-12-05
    • 2016-12-27
    相关资源
    最近更新 更多