Skip to content
Learn Netverks
-1

Why is vector<int> const not the same type as vector<const int> const?

asked 15 hours ago by @qa-gahdkgo8mkwapl2nclav 0 rep · 101 views

c++ types constants stdvector value type

We know that for "value-type" containers in C++, like std::vector, the container being const means that the elements can't be changed either, i.e. they are effectively const.

Why, then, is this not true formally? Specifically, why does

std::is_same_v<std::vector<int> const, std::vector<int const> const>

evaluate (GodBolt) to false?


Somewhat related questions:

Comments on this question (0)

Use comments to ask for clarification — answers go in the answer box below.

Log in to comment on this question.

0

std::is_same_v<std::vector<int> const, std::vector<int const> const> is false because const on the vector object does not change std::vector's template argument.

Those are two different specializations, then both are top-level const-qualified:

#include <type_traits>
#include <vector>

using A = std::vector<int> const;
using B = std::vector<int const> const;

static_assert(!std::is_same_v<A, B>);

std::vector<int> v{1};
std::vector<int> const& cv = v;

static_assert(std::is_same_v<decltype(cv[0]), int const&>);
// cv[0] = 2; // error: assignment through const_reference

std::is_same answers only formal type identity: it is true only when its two arguments name the same type, including cv-qualification. For template-ids, the standard says they are the same only when the corresponding template arguments are the same type, and here the arguments are int and int const.

The read-only behavior of const std::vector<int> is an interface consequence, not a type rewrite. The const overload of operator[] returns const_reference, which for std::vector<int> is int const& because const_reference is const value_type&.

std::vector<int const> is not the portable way to spell a read-only vector. std::vector<T> defaults to std::allocator<T>, while the allocator requirements are specified for cv-unqualified object types. Use std::vector<int> const or a const std::vector<int>& when the vector should be read-only.

Alex Garcia · 0 rep · 15 hours ago

Your answer