【发布时间】:2014-08-20 01:29:08
【问题描述】:
下面的代码将unsigned int打印为enum Test内所有常量的底层类型
#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
}
Live Example。如果Test 包含两个单独的enums,a 和b 和以前一样,也会发生这种情况。
问题:是否可以检测到Test::a 是用bool 初始化的,而Test::b 是用int 初始化的?在反射研究组的 C++17 提案中是否有任何实验代码?
注意:我知道我可以将Test 替换为
struct Test
{
static constexpr auto a = true;
static constexpr auto b = 1;
};
但我发现enum 版本的用法稍微不那么冗长。
【问题讨论】:
-
嗯。在枚举的
}之后,所有枚举数的类型都是枚举的类型。在枚举中,枚举数的类型是初始化值 [dcl.enum]/5 的类型(如果基础类型不固定)。不知道反射。 -
@dyp 我什至会满足于区分
bool和int常量的技巧。 -
@AndrewTomazos 我今天看到了你的 N4113 提案,它允许查询枚举常量values,但不能查询它们的初始化器types。你能评论一下那个设计决定吗?来自this Q&A 的赏金 :-)
-
我认为这个问题可能用词不当,因为枚举中的所有变量都具有相同的类型。当您找到 a 的类型时,您已经回答了名义上的问题。
-
@dyp:这应该是答案,而不仅仅是评论。
标签: c++ c++11 enums c++14 type-deduction