从基本数组类型切换到自定义类型时,嵌套的initializer_list初始化失败

我正在建立一个通用的数学矢量类,以供娱乐,并且我不确定此initializer_list用法是否会导致界面出问题:

struct Vertex {
    // Compiles and works fine with these two lines
    //float pos[2];
    //float color[3];

    // Does not compile with these lines
    Vector2 pos;
    Vector3 color;
};

const std::vector<Vertex> vertices = {
    { {  0.0f,-0.5f },{ 1.0f,1.0f,1.0f } },{ {  0.5f,0.5f },0.0f } },{ { -0.5f,0.1f,0.0f } }
};

核心向量实现位:

template <int size>
class Vector
{
public:
    Vector(const std::initializer_list<float>& values) : _data(values) {}

    Vector<size>& operator=(const std::initializer_list<float>& values)
    {
        _data = values;
        return *this;
    }

    // Code compiles again if I make this array public
private:
    float _data[size];
};

typedef Vector<2> Vector2;
typedef Vector<3> Vector3;

我收到的错误(使用VS2019构建):

error C2440: 'initializing': cannot convert from 'initializer list' to 'std::vector<Vertex,std::allocator<_Ty>>'
error C2440:         with
error C2440:         [
error C2440:             _Ty=Vertex
error C2440:         ]
message : No constructor could take the source type,or constructor overload resolution was ambiguous

编辑

正如有人指出的那样,它确实可以编译-我忘记了我曾尝试别名标准向量类型:

template <> 
class Vector<2> 
{ 
    union 
    { 
        float _data[2];
        struct 
        { 
            float X,Y; 
        }; 
    }; 
};

template <>
class Vector<3>
{
    union
    {
        float _data[3];
        struct
        {
            float X,Y,Z;
        };
        struct
        {
            float R,G,B;
        };
    };
};

这似乎是导致错误的原因,尽管我不确定目前是否正确的别名...

fishyuying 回答:从基本数组类型切换到自定义类型时,嵌套的initializer_list初始化失败

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3062043.html

大家都在问