Is it safe (in theory or in practice) to reinterpret_cast a std::pair<T1, T2> const & into a std::pair<T1 const, T2> const &, assuming that the programmer hasn’t intentionally done something weird like specializing std::pair<T1 const, T2>?
Is it safe (in theory or in practice) to reinterpret_cast a std::pair<T1, T2> const
Share
It’s NOT portable to do so.
std::pairrequirements are laid out in clause 20.3. Clause 17.5.2.3 clarifies thatThis implies that it’s legal (although incredibly unlikely) for an implementation to include a partial specialization such as:
which are clearly not layout-compatible. Other variations including inclusion of additional non-static data members possibly before
firstand/orsecondare also allowed under the rule.Now, it is somewhat interesting to consider the case where the layout is known. Although Potatoswatter pointed out DR1334 which asserts that
Tandconst Tare not layout-compatible, the Standard provides enough guarantees to allow us to get most of the way anyway:However this doesn’t work on
std::pairas we can’t apply 9.2p20 without knowing thatfirstis actually the initial member, which is not specified.