Reputation: 1228
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.
Upvotes: 3
Views: 759
Reputation: 126412
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;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
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;
}
Upvotes: 8