initializer_list<initializer_list<T>> 错误

Error with initializer_list<initializer_list<T>>

我想初始化我自己的class类似这样:

vector< Point3f >={{1f,2f,3f},{2f,3f,1f},{2f,2f,2f}};

但显示错误:

can't convert “initializer list” to “std::vector<LB::Point3f,std::allocator<LB::Point3f>>...

我想知道用大括号中的列表初始化我自己的 class 的正确方法是什么。

这是我的代码:

#pragma once
#ifndef POINT_HPP
#define POINT_HPP

#include<initializer_list>

namespace LB
{
    using namespace std;

    template< typename T,unsigned length>
    class Point
    {
        T data[length];
    public:
        Point(){}
        Point(const initializer_list<T>& t)
        {
            int min = t.size() < length ? t.size() : length;
            int i = 0;
            for (auto& each : t)
            {
                if (i >= min)
                    break;
                data[i] = each;
                i++;
            }
        }
        Point(Point<T, length>& other)
        {
            for (int i = 0; i < length; i++)
            {
                data[i] = other[i];
            }
        }
/*
   other operation function
*/
    };

    using Point2i = Point<int, 2>;
    using Point2f = Point<float, 2>;
    using Point2d = Point<double, 2>;
    using Point3i = Point<int, 3>;
    using Point3f = Point<float, 3>;
    using Point3d = Point<double, 3>;
    using Point4i = Point<int, 4>;
    using Point4f = Point<float, 4>;
    using Point4d = Point<double, 4>;
}

#endif

基本上它失败了,因为您当前的 `Point 实现没有有效的复制构造函数。

复制构造函数需要采用 const Point<T, length>&,因为初始化列表是常量,并且需要 const 版本的 operator[],考虑到您当前的复制实现,因为复制构造函数的参数是对自定义点 class 的引用,而不是数组。

代码如下:

#include <iostream>
#include<initializer_list>
#include <vector>

namespace LB
{
    template< typename T, unsigned length>
    class Point
    {
        T data[length];
    public:
        Point() {}
        Point(const std::initializer_list<T>& t)
        {
            int min = t.size() < length ? t.size() : length;
            int i = 0;
            for (auto& each : t)
            {
                if (i >= min)
                    break;
                data[i] = each;
                i++;
            }
        }

        Point(const Point<T, length>& other)
        {
            for (size_t i = 0; i < length; i++)
            {
                data[i] = other[i];
            }
        }

        T& operator[](size_t i) {
            return data[i];
        }
   
        const T& operator[](size_t i) const {
            return const_cast<const T&>(
                const_cast<Point&>(*this)[i]
            );
        }
    };

    using Point3f = Point<float, 3>;
}

int main() {
    std::vector<LB::Point3f> vec = { {1.0f,2.0f,3.0f},{2.0f,3.0f,1.0f},{2.0f,2.0f,2.0f} };
    std::cout << vec[1][0] << " , " << vec[1][1] << " , " << vec[1][2] << "\n";
}