P0138R2提案以1开头。
There is an incredibly useful technique for introducing a new integer type that is almost an exact copy, yet distinct type in modern C++11 programs: an
enum class
with an explicitly specified underlying type. Example:
enum class Index : int { }; // Note: no enumerator.
One can use
Index
as a new distinct integer type, it has no implicit conversion to anything (good!).
将 Index
转换为其基础类型时,定义以下内容可能很有用:
int operator*(Index index) {
return static_cast<int>(index);
}
创建 Index
类型的另一种方法是使用旧的 class
:
class Index final {
public:
explicit Index(int index = 0) : index_(index) { }
int operator*() const {
return index_;
}
private:
int index_;
};
两者似乎在很大程度上是等同的,可以以相同方式使用:
void bar(Index index) {
std::cout << *index;
}
bar(Index{1});
int i = 1;
bar(Index{i});
enum class
的优点:比较操作符自动定义,enum class
的缺点:无法指定默认构造的enum class
的索引值,它总是零。这些替代方案还有其他实际差异吗?
注1:我将
uint32_t
更改为int
,以避免使用#include <cstdint>
。
operator*
应该返回一个引用吗? - Rakete1111enum class
,您无法定义转换或赋值运算符。 - geza