gpt4 book ai didi

c++ - const强制转换为非指针非引用类型

转载 作者:行者123 更新时间:2023-12-02 10:19:06 27 4
gpt4 key购买 nike

[expr.const.cast]/3:

For two similar types T1 and T2, a prvalue of type T1 may be explicitly converted to the type T2 using a const_­cast if, considering the cv-decompositions of both types, each Pi1 is the same as Pi2 for all i. The result of a const_­cast refers to the original entity.



似乎const强制转换为非指针非引用类型是允许的。例如,以下功能
void f(int a)
{
const_cast<int>(a);
}

应该格式正确,因为 intint肯定是相似的类型,并且在cv分解中没有Pi(因此“每个Pi1与所有i的Pi2相同”的主张应该成立)。

但是,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);
| ^

GCC:
<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);
| ^~~~~~~~~~~~~~~~~~

我是否缺少某些内容?或者它是编译器错误?

UPDATE :这不起作用,或者:
void f()
{
const_cast<int>(int{});
}

最佳答案

在C++ 17中,类型不同,因此引用的文本不适用。因此,不允许此const_cast,因为除非明确允许,否则不允许const_cast

C++ 17 [conv.qual] / 1:

A cv-decomposition of a type T is a sequence of cvi and Pi such that T is

“cv0 P0 cv1 P1 ··· cvn-1 Pn-1 cvn Ufor n > 0,

where each cvi is a set of cv-qualifiers (6.9.3), and each Pi is “pointer to” (11.3.1), “pointer to member of class Ci of type” (11.3.3), “array of Ni ”, or “array of unknown bound of” (11.3.4). [...]



然后

Two types T1 and T2 are similar if they have cv-decompositions with the same n such that corresponding Pi components are the same and the types denoted by U are the same.



要求 n> 0 意味着必须存在cv0 P0,即该类型中至少有一个指针。

最新的C++ 20草案由于 Issue 2051 n> 0 更改为 n≥0 。但是不更改 const_cast的规范。我不能说这是故意还是疏忽。

因此,C++ 20可能会使您的 const_cast表达式定义良好,并且编译器将不得不跟上。

关于c++ - const强制转换为非指针非引用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61003855/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com