c++ - 将 std::pair<T1, T2> const 转换为 std::pair<T1 const, T2> const 安全吗?

标签 c++ templates casting constants reinterpret-cast

reinterpret_cast 是否安全(理论上或实际上)一个 std::pair<T1, T2> const &变成 std::pair<T1 const, T2> const & ,假设程序员没有故意做一些奇怪的事情,比如专门 std::pair<T1 const, T2> ?

最佳答案

这样做并不便携。

std::pair 要求在第 20.3 节中列出。第 17.5.2.3 条阐明了

Clauses 18 through 30 and Annex D do not specify the representation of classes, and intentionally omit specification of class members. An implementation may define static or non-static class members, or both, as needed to implement the semantics of the member functions specified in Clauses 18 through 30 and Annex D.

这意味着实现包含部分特化是合法的(尽管极不可能),例如:

template<typename T1, typename T2>
struct pair<T1, T2>
{
    T1 first;
    T2 second;
};

template<typename T1, typename T2>
struct pair<const T1, T2>
{
    T2 second;
    const T1 first;
};

显然不兼容布局。该规则还允许其他变体,包括可能在 first 和/或 second 之前包含额外的非静态数据成员。


现在,考虑一下布局已知的情况有点有趣。虽然 Potatoswatter 指出 DR1334它断言 Tconst T 不是 layout-compatible,标准提供了足够的保证,让我们无论如何都能获得大部分的结果:

template<typename T1, typename T2>
struct mypair<T1, T2>
{
    T1 first;
    T2 second;
};

mypair<int, double> pair1;
mypair<int, double>* p1 = &pair1;
int* p2 = reinterpret_cast<int*>(p1); // legal by 9.2p20
const int* p3 = p2;
mypair<const int, double>* p4 = reinterpret_cast<mypair<const int, double>*>(p3); // again 9.2p20

但是,这在 std::pair 上不起作用,因为我们无法在不知道 first 实际上是初始成员的情况下应用 9.2p20,但未指定.

关于c++ - 将 std::pair<T1, T2> const 转换为 std::pair<T1 const, T2> const 安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14272141/

相关文章:

c++ - 如何将元素附加到 vector 函数?

c++ - 为每个函数和自由函数 boost mpl

c++ - 为什么 GCC 认为模板参数是 int 而它是完全不同的类型?

typescript - 将接口(interface)转换为字典

c++ - 在 C 中将 double 转换为整数时处理溢出

c++ - 在 C/C++ 中进行数学运算时,我应该对哪些变量进行类型转换?

java - 迭代性能 Java 与 C++

c# - 如何将 C 数组映射到 C#?

c++ - Cython:为什么是 "duplicate symbol"?

templates - 如何将新模板添加到 Typo3 "Layouts"下拉列表