【问题标题】:initializer list vector constructor初始化列表向量构造函数
【发布时间】:2016-01-10 17:35:59
【问题描述】:

我正在尝试定义一个带有 initializer_list 参数的类构造函数,并使用它来构造包含的向量。

//header
template<typename VertexType, typename IndexType>
class Mesh
{
public:
    Mesh(std::initializer_list<VertexType> vertices);
private:
    std::vector<VertexType> mVertexData;
};

// cpp
template<typename VertexType, typename IndexType>
Mesh<VertexType, IndexType>::Mesh(std::initializer_list<VertexType> vertices)
{
    mVertexData(vertices);
}

编译失败并出现以下错误:

error: no match for call to '(std::vector<Vertex,
std::allocator<Vertex> >) (std::initializer_list<NRK::Vertex>&)'
mVertexData(vertices);

不知道我做错了什么。有什么提示吗?

我正在使用 QTCreator 5.4.2 和 MinGW 在 Windows 上进行编译。

【问题讨论】:

    标签: c++ c++11 vector initializer-list


    【解决方案1】:

    您正在尝试在完全创建的 vector 上调用呼叫操作员 (operator())。
    您应该使用 ctor-init-list 中的构造函数(首选),或者调用成员函数 assign

    template<typename VertexType, typename IndexType>
    Mesh<VertexType, IndexType>::Mesh(std::initializer_list<VertexType> vertices)
    : mVertexData(vertices)
    {}
    

    顺便说一句,您真的确定在该实现文件中定义模板的成员会起作用吗?
    你真的在那里实例化了所有需要的专业化吗?

    【讨论】:

    • 不确定..只是随便玩玩..我有一组有限的openGL VBO数据布局类型,所以我可能就是这种情况。
    • 好吧,玩得开心。这样做的问题是你真的必须确保它,而且总的来说这太麻烦了。
    • @Decuplicator:我可能不想让客户端类专门化具有任意类型的模板类。它现在是一个模板,只是为了让我保存一些代码。无论如何..我只是在玩:)..谢谢你的回答,你帮我解决了我的愚蠢错误..
    猜你喜欢
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2019-03-04
    • 2012-03-19
    相关资源
    最近更新 更多