Class vs enum class as an index type

孤者浪人 提交于 2020-06-27 07:23:34

问题


P0138R2 proposal begins with1

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!).

To convert Index to its underlying type it is useful to define

int operator*(Index index) {
    return static_cast<int>(index);
}

Another way to create Index type is to use old class:

class Index final {
public:
     explicit Index(int index = 0) : index_(index) { }

     int operator*() const {
         return index_;
     }

private:  
     int index_;
};

Both seem to be largely equivalent and can be used in the same way:

void bar(Index index) {
    std::cout << *index;
}

bar(Index{1});

int i = 1;
bar(Index{i});

Pro of enum class: the comparison operators are defined automatically, con of enum class: index value for the default constructed enum class can't be specified, it is always zero.

Are there other practical differences between these alternatives?


1 I changed uint32_t to int to avoid #include <cstdint>.

来源:https://stackoverflow.com/questions/52045697/class-vs-enum-class-as-an-index-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!