24n8
24n8

Reputation: 2236

decltype on an element of std::vector

Why does the following not compile?

  std::vector<int> v{1,2};
  decltype(v[0]) i;           //doesn't work
  decltype(v)::value_type j;  //works

I receive the error test.cpp:31:18: error: declaration of reference variable 'i' requires an initializer. Isn't v[0] of type int here?

I understand that even if it did work, it wouldn't be as safe as the latter in case the vector is empty, but I feel that should be a runtime issue rather than a compile time issue.

Upvotes: 0

Views: 726

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136266

decltype(v[0]) yields you the type of expression v[0] which is a reference to the element (unless v is vector<bool>). A reference variable must be initialized, and that is what the compiler error message says.

You can use auto to get an element by value and auto& to get it by reference:

auto element = v[0];
auto& element_ref = v[0];

Upvotes: 1

Related Questions