【问题标题】:reinterpret_cast to the same typereinterpret_cast 到相同的类型
【发布时间】:2020-02-14 04:07:01
【问题描述】:

考虑以下程序:

struct A{};

int main()
{
    A a;
    A b = a;
    A c = reinterpret_cast<A>(a);
}

编译器(g++14) 抛出关于invalid cast from type 'A' to type 'A' 的错误。 为什么强制转换为同一类型无效?

【问题讨论】:

  • 这是一个有用的问题,因为我也想这样做是出于一个特殊的原因:当解决不支持 if constexpr 的旧编译器的问题时,这允许一个虚拟转换对象的机制 (引用)在模板化表达式中引用它自己的已知类型,因此在没有添加许多额外的启用 SFINAE 的辅助函数的情况下仍然可以编译。

标签: c++ c++14 standards reinterpret-cast


【解决方案1】:

reinterpret_cast 应该用于指针、引用和整数类型。

我不知道,为什么有人这样做。

但你还是想做。你可以做。

 A *d = reinterpret_cast<A*>(&a);

A c = reinterpret_cast<A&>(a);

【讨论】:

    【解决方案2】:

    因为reinterpret_cast不能用于类和结构,它应该用于重新解释指针、引用和整数类型。 cpp reference中解释的很好

    因此,在您的情况下,一种可能的有效表达式是 reinterpret_cast&lt;A*&gt;(&amp;a)

    【讨论】:

    • reinterpret_cast&lt;A&amp;&gt;(a);
    【解决方案3】:

    这是不允许的,因为标准是这样说的。

    您可以使用reinterpret_cast 进行一组相当有限的允许转换。参见例如cppreference。例如那里列出的第一点是:

    1) 整数、枚举、指针或 指向成员的类型可以转换为它自己的类型。所结果的 值与表达式的值相同。 (C++11 起)

    但是,将自定义类型(没有指针!)转换为自身不在列表中。你为什么要这样做?

    【讨论】:

    • 另见expr.reinterpret.cast。您知道为什么允许将列出的类型转换为自身吗?
    • @lubgr 这是一个有趣的问题,我猜想 c++11 中的其他东西需要添加该功能,因为它本身看起来没什么用
    • @lubgr 如果您打开一个,请联系我。 reinterpret_cast 一直是我困惑的根源,这是我想我永远不会停止学习新东西的主题之一
    • Ping...这里是question
    猜你喜欢
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多