Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass container value_type as template parameter?

Tags:

c++

templates

stl

is it possible to pass the value_type of a container as a template parameter?

something like:

template<typename VertexType>
class Mesh
{
    std::vector<VertexType> vertices;
};

std::vector<VertexPositionColorNormal> vertices;

// this does not work, but can it work somehow?
Mesh<typename vertices::value_type> mesh;

// this works, but defeats the purpose of not needing to know the type when writing the code
Mesh<typename std::vector<VertexPositionColorNormal>::value_type> mesh;

i get a "invalid template argument" when creating the mesh (the first one), but it should work right? i'm passing a known type at compile time, why doesn't it work? what alternatives are there?

thanks.

like image 277
sap Avatar asked Apr 10 '26 07:04

sap


1 Answers

In C++11 you can use decltype:

    Mesh<decltype(vertices)::value_type> mesh;
//       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

A full compiling example would be:

#include <vector>

struct VertexPositionColorNormal { };

template<typename VertexType>
class Mesh
{
    std::vector<VertexType> vertices;
};

int main()
{
    std::vector<VertexPositionColorNormal> vertices;

    Mesh<decltype(vertices)::value_type> mesh;
//       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}

Live example.

If you are limited to C++03, on the other hand, the best you can do is probably to define a type alias:

int main()
{
    std::vector<VertexPositionColorNormal> vertices;

    typedef typename std::vector<VertexPositionColorNormal>::value_type v_type;

    // this does not work, but can it work somehow?
    Mesh<v_type> mesh;
}
like image 116
Andy Prowl Avatar answered Apr 12 '26 19:04

Andy Prowl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!