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
· 5 hours ago