[英]How do I access a constexpr created type as another type while staying constexpr? (using with static_assert)
我一直在试图弄清楚这一点,并认为看一看会很有趣:)
好的,所以我正在使用位域将类型创建为constexpr。 由于位域可以从一种实现或平台更改为另一种实现或平台,因此我想static_assert确定位在正确的位置。 到目前为止和我在一起? 这是我要创建的类型的代码:
// Currently hard-coded for 64bit, will change later when I get past this part...
constexpr int getPointerBitCount() { return 64; }
constexpr int getPointerByteWidth() { return getPointerBitCount() / 8; }
constexpr int getPointerDataWidth() { return 3; }
constexpr int getPointerPointerWidth() { return getPointerBitCount() - getPointerDataWidth(); }
struct PointerData
{
bool _invalid :1;
bool _delete :1;
bool _unused :1;
uint64_t _pointer :getPointerPointerWidth();
constexpr PointerData(bool invalid, bool isDelete, bool unused)
: _invalid{invalid}
, _delete{isDelete}
, _unused{unused}
, _pointer{0}
{
}
};
所以现在我想做的是:
static_assert(reinterpret_cast<uint64_t>(PointerData(true, false, false)) == 1, "PointerData not supported on this platform");
static_assert(reinterpret_cast<uint64_t>(PointerData(false, true, false)) == 2, "PointerData not supported on this platform");
static_assert(reinterpret_cast<uint64_t>(PointerData(false, false, true)) == 4, "PointerData not supported on this platform");
基本上,我需要将PointerData类型创建为constexpr,然后对它进行测试,就好像整个事情都是uint64_t(或32位的uint32_t)一样。 但是,我的编译器说我不能在这里使用reinterpret_cast。 关于如何做到这一点的想法?
运行按位运算符来计算值将无法实现我想要的功能。 我需要按原样访问变量。 这里的测试是查看位域中的第一位是否等于1(第二位= 2,第三位= 4)。
我考虑过以此创建联合,但是我不确定给定位域是否合适。 不确定
我是constexpr的新手,所以将不胜感激!
reinterpret_cast
与static_assert
不兼容,即使其行为定义明确,但您的用法具有特定于实现的行为。 如果执行这样的强制转换,将允许编译器拒绝此类代码,或者将使计算机崩溃并燃烧。
要使其正常工作,请在PointerData
添加一个constexpr operator uint64_t () const
以返回您希望reinterpret_cast
产生的值。 然后将reinterpret_cast
更改为static_cast
。
编辑:不,C ++不支持您尝试的内容。 常量表达式评估(如constexpr
要求)要求编译器在某种程度上模拟目标平台。 需要此仿真器将未定义的行为标记为错误,以及许多特定于实现的情况(包括所有reinterpret_cast
表达式)。
您的reinterpret_cast
的体系结构不起作用,因为它正在模拟器内进行自省。 您需要将其移至构建系统“ canary”或启动程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.