【发布时间】:2021-09-04 10:50:31
【问题描述】:
我遇到了以下错误:
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 中不允许这样的演员表?
【问题讨论】:
-
编译器是否将
reinterpret_cast用于(T*)取决于转换的类型和转换为的类型。如果它与(T*)一起工作,那么编译器没有选择reinterpret_cast -
有了标题,问题可能与Why is reinterpret_cast not constexpr? 重复您可能希望显示带有使用模板的minimal reproducible example 和
(T*)的代码,包括与演员表和您当前的示例也是如此,然后可以说明为什么一个有效而另一个无效 -
不是答案;但是如果你用
unsigned int(或64位环境中的unsigned long)替换int*,它编译时不会出现警告。 -
这可能是最好的,因为不要认为这是一个有效的演员表。您将如何到达
char数组的最后一个元素? -
哦,当我有自己的具有 char 缓冲区的数组容器时,它出现了,我无法通过 char 指针在调试器中看到其中的任何内容,所以我想创建一个调试指针投射到 T。