gpt4 book ai didi

显式类型转换(C 风格转换)的 C++ 转换符号和 static_cast 的多种解释

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:50:02 25 4
gpt4 key购买 nike

Paragraph 4 of [expr.cast] (在撰写本文时可用的最新 C++ 标准草案中)描述了 C 样式转换的行为如下:

The conversions performed by

  • a const_­cast,
  • a static_­cast,
  • a static_­cast followed by a const_­cast,
  • a reinterpret_­cast, or
  • a reinterpret_­cast followed by a const_­cast,

can be performed using the cast notation of explicit type conversion. The same semantic restrictions and behaviors apply, with the exception that in performing a static_­cast in the following situations the conversion is valid even if the base class is inaccessible:

  • a pointer to an object of derived class type or an lvalue or rvalue of derived class type may be explicitly converted to a pointer or reference to an unambiguous base class type, respectively;
  • a pointer to member of derived class type may be explicitly converted to a pointer to member of an unambiguous non-virtual base class type;
  • a pointer to an object of an unambiguous non-virtual base class type, a glvalue of an unambiguous non-virtual base class type, or a pointer to member of an unambiguous non-virtual base class type may be explicitly converted to a pointer, a reference, or a pointer to member of a derived class type, respectively.

If a conversion can be interpreted in more than one of the ways listed above, the interpretation that appears first in the list is used, even if a cast resulting from that interpretation is ill-formed. If a conversion can be interpreted in more than one way as a static_­cast followed by a const_­cast, the conversion is ill-formed. [...]

我的问题是“转换如何以不止一种方式解释为 static_cast 后跟 const_cast”?

谢谢。

最佳答案

像这样:

struct S {
operator int const**() { return nullptr; }
operator int *const*() { return nullptr; }
};

S s;
(int**)s; // error: cannot cast from type 'S' to pointer type 'int **'

int const**int *const* 的类似转换成功。 Demo

关于显式类型转换(C 风格转换)的 C++ 转换符号和 static_cast 的多种解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52571794/

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