代码之家  ›  专栏  ›  技术社区  ›  paulm

如何将具有var长度的编译时数组传递给构造函数?

  •  0
  • paulm  · 技术社区  · 7 年前

    我有以下代码:

    struct MyArrayEntry
    {
        int type;
        int id;
    };
    
    template<size_t arraySize>
    struct MyArray
    {
        template<typename T, typename... Types>
        MyArray(T t, Types... ts) : data{ { t, ts... } } {}
        int dataSize = arraySize;
        MyArrayEntry data[arraySize];
    };
    
    
    void Blah()
    {
     static MyArray<3> kTest
                (
                    { 1, 4 },
                    { 2, 5 },
                    { 3, 6 }
                );
    }
    

    但这不能建立在:

    错误C2661:“MyArray”<3>::MyArray”:重载函数不接受3 论据

    我在这里做错什么了?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Some programmer dude    7 年前

    根据你提供的信息,我建议使用 std::initializer_list 还有一个 std::copy 呼叫:

    template<size_t arraySize>
    struct MyArray
    {
        const int dataSize = arraySize;  // Could as well make it constant
        MyArrayEntry data[arraySize];
    
        MyArray(std::initializer_list<MyArrayEntry> elements)
        {
            std::copy(begin(elements), end(elements), std::begin(data));
        }
    };
    

    创建为

    MyArray<3> kTest({ { 1, 4 }, { 2, 5 }, { 3, 6 } });
    

    当然是另外一对花括号 {} ,但它将使代码更简单。