asmmo
asmmo

Reputation: 7100

decltype() doesn't work for class template being compiled

I have the following snippet of code having a problem. I think the compiler can't deduc the type because the type of the elements of values won't b known before compiling. Is that right?

vector values{1, 2, 3, 4, 5, 6};
vector<decltype(values[0])> {values};
ostream_iterator<int> printer{cout," "};
copy(ints.crbegin(),ints.crend(),printer);

Upvotes: 1

Views: 95

Answers (1)

Indiana Kernick
Indiana Kernick

Reputation: 5331

The problem here is that values[0] is a int &. See for yourself:

static_assert(std::is_same_v<decltype(values[0]), int &>);

Creating a vector of references is all kinds of wrong. To fix this, just use decltype on the whole vector.

std::vector values{1, 2, 3, 4, 5, 6};
decltype(values) ints(values.cbegin(), values.cend());

For your example, none of this is really necessary because you're just copying a vector. So you can just do this:

std::vector ints = values;
// Or avoid CTAD entirely
auto ints = values;

Upvotes: 5

Related Questions