4

Suppose I have a vector like this:

std::vector<int> vec;

Then I want to know the type of vec's elements. How can I get it? Too bad decltype(vec[0]) results in int&.

  • Does this answer your question? [check type of element in stl container - c++](https://stackoverflow.com/questions/1708867/check-type-of-element-in-stl-container-c) – user202729 Feb 16 '21 at 16:00
  • The VS2010 bug is [c++ - How to get element type from STL container instance? - Stack Overflow](https://stackoverflow.com/questions/12391814/how-to-get-element-type-from-stl-container-instance) – user202729 Feb 16 '21 at 16:01

2 Answers2

7

Is this what you're looking for?

std::vector<int>::value_type

You can also use

std::remove_reference<decltype(vec[0])>::type

to get rid of the reference.

Another option is to use decltype(vec)::value_type. However, this doesn't currently work on Visual Studio due to a compiler bug. A workaround for that compiler is to create an intermediate typedef.

typedef decltype(vec) vec_type;
vec_type::value_type foo;
Praetorian
  • 106,671
  • 19
  • 240
  • 328
  • It would be better if there is something like `decltype(vec)::value_type`. –  May 12 '13 at 03:36
  • 2
    @Mike That does work. You're using MSVC aren't you? There's a bug in the compiler that causes errors if you write `::` after any `decltype` expression. – Praetorian May 12 '13 at 03:38
  • Another workaround for MSVC is using std::identity::type::value_type – GalDude33 Jan 11 '16 at 09:33
  • @GalDude33 `std::identity` is non-standard. It appeared in some pre-standardization C++0x drafts but was dropped somewhere along the way. – Praetorian Jan 12 '16 at 00:52
  • std::identity does exist in VS (checked on VS2010) - where a bug denies you simply writing decltype(vec)::value_type – GalDude33 Jan 18 '16 at 21:58
0

For object, c, of any container type including arrays and all standard library containers such as std::vector and std::list:

typename std::remove_reference<decltype(*std::begin(c))>::type

John McFarlane
  • 5,528
  • 4
  • 34
  • 38