c++ - 为什么不能在常量表达式中使用 reinterpret_cast?

标签 c++ constexpr

<分区>

我遇到了以下错误:

class NormalClass
{
public:
    constexpr NormalClass() : arr{}, debug_ptr((int*)arr)
    {
//'reinterpret_cast' is not a constant expression
//cast that performs the conversions of a reinterpret_cast is not allowed in a constant expression
    }

public:

    char arr[5];
    int* debug_ptr;


};

constinit NormalClass normal;

int main()
{

}

最初这是在一个模板中,带有 (T*) 转换。为什么在 constexpr 中不允许这样的转换?

最佳答案

参见 https://en.cppreference.com/w/cpp/language/constant_expression

核心常量表达式

核心常量表达式是其计算不会计算以下任何一项的任何表达式:

  • >
    1. 重新解释_cast

关于c++ - 为什么不能在常量表达式中使用 reinterpret_cast?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69054606/

相关文章:

c++ - 从文件 C++ 中读取一个单词的类

c++ - std::string size() 是 O(1) 操作吗?

c++ - constexpr vector push_back 或如何 constexpr 所有的东西

c++ - constexpr 函数包含一个 const - 它会在编译时被评估吗?

c++ - 在 C++ 中将信息写入文件的函数

c++ - 函数模板 c++ 的显式特化

c++ - 为什么这个 constexpr if 不能编译

C++ 强制非 constexpr 上下文

c++ - 什么决定了 constexpr 函数是否是常量表达式?

c++ - 从 unordered_map 存储和检索后对象发生变化