Home > OS >  C decltype failed on vector elem
C decltype failed on vector elem

Time:11-26

template <typename T>
void F(T&) { std::cout << __FUNCTION__ << "\n"; }

template <typename T>
void F(vector<T>&) { std::cout << __FUNCTION__ << "\n"; }

int main()
{
    int x = 0;
    F<decltype(x)>(x);      // this line compile and works fine
    
    vector<int> v;
    F<decltype(v[0])>(v);                       // this line won't compile
    F<remove_reference<decltype(v[0])>>(v);     // Neither this one
}

Why wouldn't F<decltype(v[0])>(v); work?

CodePudding user response:

First, you do not have a v[0]. Even if you do have elements in v,* decltype(v[0]) will be int&, hence F<decltype(v[0])>(v) fails.

Note*: more in the comment about why having elements in v or not doesn't matter.


Second, remove_reference<decltype(v[0])> is the name of a struct, not a type. To properly get the type from it, you should call:

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

Or:

std::remove_reference_t<decltype(v[0])>
                     ^^

Also, instead of using remove_reference, you can simply get the element type of a vector with ::value_type:

F<decltype(v)::value_type>(v); 

Demo

  • Related