Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the type of the elements in a vector?

Considering template metaprogramming techniques if I have

std::vector<int> v;
v.push_back(42.42f);

this works, mainly because the constructor being used it's not marked explicit, in other words my push_back it's not type safe.

Now I'm in a situation where I don't even know how a container v is declared, in this case it's int, but I need to deduce the type automatically while having a generic std::vector<T>. I would like a solution to get T.

in C++11 there is something like remove_all_extents ( with an useful member type ) but apparently it's only useful for the old arrays, but it's basically what I would like to achieve.

I would like to trigger an error when the push_back it's not type safe or deduce the type so I can write an assertion or implement something on my own.

I really can't find a working solution for this, it's so simple in theory, but once a vector is declared there is no explicit information about the type used for the elements.

I also would like to avoid explicit type inference, like translating foo from my ideal function call

foo( container, elements ... )

to

foo<int>(container, elements ...)

where int is the type for the elements of container, this is not safe too in my opinion, it's also more verbose and error prone.

So how do I retrieve the type for the elements of a container in C++11 ?

like image 600
user2485710 Avatar asked Jan 28 '14 07:01

user2485710


1 Answers

You can get the type like this:

typename std::vector<T>::value_type;

Then use static_assert together with std::is_same.

template <typename T1, typename T2>
void special_push_back(std::vector<T1>& v, T2 elem)
{
  // check that T1 and T2 are the same before pushing elem into v
}

then

std::vector<int> v;
special_push_back(v, 3.14); // Compile time error: double is not int
like image 157
juanchopanza Avatar answered Oct 24 '22 21:10

juanchopanza