Search code examples
c++11decltype

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.


Solution

  • 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];