为什么我不能 std::bit_cast 字符串文字的内容?

Jan*_*tke 7 c++ type-punning c++20 bit-cast

在尝试编译时字符串操作时,我遇到了一个奇怪的现象:

#include <bit>

constexpr const char str[4] = "abc";

// error: constexpr variable 'x' must be initialized by a constant expression
constexpr auto x = std::bit_cast<int>("xyz");
// OK
constexpr auto y = std::bit_cast<int>(str);
Run Code Online (Sandbox Code Playgroud)

请参阅编译器资源管理器

为什么允许对char[]存储在全局变量中的 a进行位转换,但不允许对字符串文字进行位转换?std::bit_cast不修改其源并且结果是一个值,因此没有修改字符串文字存储的潜力。

Jan*_*tke 1

std::bit_cast<int>("xyz")常量表达式中的值在 C++20 中有效。没有违反[bit.cast] p3中的任何标准,也没有违反前一段中的任何先决条件。

由于编译器错误,它无法在 clang 中编译。请参阅llvm-project 问题 #63686

没有人想到普通 C++ 中的数组可以进行左值到右值的转换,但 LLVM 的实现需要std::bit_cast它(请参阅ExprConstant.cpp):

if (LVal.Designator.Entries.empty()) {
  // Fail for now for LValue to RValue conversion of an array.
  // (This shouldn't show up in C/C++, but it could be triggered by a
  // weird EvaluateAsRValue call from a tool.)
  Info.FFDiag(Conv);
  return false;
}
Run Code Online (Sandbox Code Playgroud)