【发布时间】:2020-07-15 03:34:28
【问题描述】:
对于两个相似的类型 T1 和 T2,类型 T1 的纯右值可能是 如果使用 const_cast 显式转换为 T2 类型, 考虑到这两种类型的 cv 分解,每个 Pi1 是 与所有 i 的 Pi2 相同。 const_cast 的结果是指 原始实体。
似乎允许将 const 强制转换为非指针非引用类型。比如下面这个函数
void f(int a)
{
const_cast<int>(a);
}
应该是格式正确的,因为int 和int 肯定是相似的类型并且在他们的简历中没有Pi -分解(因此“每个 Pi1 与 P em>i2 for all i" 应该为真)。
但是,GCC 和 Clang 都拒绝上面的代码(请参阅Compiler Explorer)。错误消息是
叮当声:
<source>: In function 'void f(int)':
<source>:3:22: error: invalid use of const_cast with type 'int', which is not a pointer, reference, nor a pointer-to-data-member type
3 | const_cast<int>(a);
| ^
海合会:
<source>: In function 'void f(int)':
<source>:3:5: error: invalid use of 'const_cast' with type 'int', which is not a pointer, reference, nor a pointer-to-data-member type
3 | const_cast<int>(a);
| ^~~~~~~~~~~~~~~~~~
是我遗漏了什么还是编译器错误?
更新:这也不起作用:
void f()
{
const_cast<int>(int{});
}
【问题讨论】:
-
a参数不是 prvalue,它是 lvalue,因此转换失败的原因。 -
@RemyLebeau 谢谢,请查看我编辑的问题
-
@RemyLebeau 左值可能被隐式转换为纯右值
-
我昨天看了这个,因为有人问类类型的左值转换可能发生在哪里;如果非指针类型相似,则
T t; const_cast<T>(t)将是一个示例(这将实现临时)
标签: c++ language-lawyer const-cast