以下代码将
enum Test
中所有常量的基础类型打印为unsigned int
。#include <iostream>
#include <type_traits>
#include <typeinfo>
#include <cxxabi.h>
struct Test
{
enum { a = true, b = 1 };
};
static_assert(std::is_same<
std::underlying_type_t<decltype(Test::a)>,
std::underlying_type_t<decltype(Test::b)>>::value, ""
);
int main()
{
int status;
auto const& bi = typeid(std::underlying_type_t<decltype(Test::a)>);
std::cout << abi::__cxa_demangle(bi.name(), 0, 0, &status); // unsigned int
}
实时示例。如果Test
包含两个独立的enum
,其中包含与之前相同的a
和b
,则也会发生这种情况。
问题:是否有可能检测到Test::a
使用bool
初始化,而Test::b
使用int
?在C++17的Reflection Study Group提案中是否有任何实验性代码可用于此?
注意:我知道我可以通过将Test
替换为...
struct Test
{
static constexpr auto a = true;
static constexpr auto b = 1;
};
但我发现在使用上enum
版本稍微不那么冗长。
}
之后,所有枚举器的类型都是枚举的类型。在枚举中,如果底层类型没有固定,那么枚举器的类型是初始化值的类型 [dcl.enum]/5。我不知道反射相关的内容。 - dypbool
和int
常量的技巧。 - TemplateRex