Search code examples
c++c++11vectorinitializer-list

initializer list vector constructor


I am trying to define a class constructor which takes and initializer_list parameter and use it to construct the contained vector.

//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);
}

The compilation fails with the following error:

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

Not sure what I am doing wrong. Any hint?

I am compiling on Windows using QTCreator 5.4.2 and MinGW.


Solution

  • You are trying to call the call-operator (operator()) on a fully created vector.
    You should either use the constructor in the ctor-init-list (preferred), or call the member-function assign.

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

    As an aside, are you really sure defining members of your template in that implementation-file will work?
    You really instantiate all needed specializations there?