Student4K
Student4K

Reputation: 951

Container type and compile-time type deduction

I want to have a vector of integers and some code, that processes that vector in a most general way (at compile-time) w.r.t. the vector element type. E.g.:

std::vector<uint16_t> X;
...
X.push_back(rand() % std::numeric_limits<X::value_type>::max());

But the compiler says:

the value of X is not usable in a constant expression

Why cannot X::value_type be used in such a context? I mean X's element type cannot change once it is declared with concrete element type, and this can be deduced from syntax of this piece of code alone. And what should be the approach if I change the declared X's element type (another integer), but do not want to change the push_back string due to that change? I am assuming any modern C++ standard.

Upvotes: 2

Views: 79

Answers (2)

songyuanyao
songyuanyao

Reputation: 172924

X is the name of the object, not the type. You can use decltype (since C++11) to get the type of X.

X.push_back(rand() % std::numeric_limits<decltype(X)::value_type>::max());

Upvotes: 1

bobah
bobah

Reputation: 18864

If you change it to call value_type on a type (instead of an instance - I don't think that's a valid C++) it will compile and work (godbolt).

using vec_t = std::vector<uint16_t>;
vec_t X;
// or the other way around:
// auto X = std::vector<uint16_t>();
// using vec_t = decltype(X);
X.push_back(rand() % std::numeric_limits<vec_t::value_type>::max());

Upvotes: 1

Related Questions