我正在寻找一种在编译时将类型映射到数值的方法,理想情况下不使用本答案中建议的散列。
由于指针可以constexpr,我试过这个:
struct Base{};
template<typename T> struct instance : public Base{};
template<typename T>
constexpr auto type_instance = instance<T>{};
template<typename T>
constexpr const Base* type_pointer = &type_instance<T>;
constexpr auto x = type_pointer<int> - type_pointer<float>; // not a constant expression
Run Code Online (Sandbox Code Playgroud)
gcc 和 clang 都拒绝此代码,因为type_pointer<int> - type_pointer<float>它不是一个常量表达式,例如,请参见此处。
为什么?
我可以理解,从一个编译到下一个编译,这两个值之间的差异不会稳定,但在一个编译中,它应该是constexpr,恕我直言。