类与枚举类作为索引类型

2024-05-01

P0138R2 proposal http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0138r2.pdf begins with1

有一种非常有用的技术可以引入一种新的整数类型,该类型几乎是精确的副本,但在现代 C++11 程序中是不同的类型:enum class具有明确指定的基础类型。例子:

enum class Index : int { };    // Note: no enumerator.

一个可以用Index作为一种新的不同整数类型,它没有任何隐式转换(很好!)。

转换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});

Pro of enum class:比较运算符是自动定义的,con ofenum class:默认构造的索引值enum class无法指定,它始终为零。

这些替代方案之间还有其他实际差异吗?


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

我使用的强类型的替代方案是命名类型 https://github.com/joboccara/namedtype作者:乔纳森·博卡拉。他在他的博客上的多篇文章中很好地解释了所有细节,请参阅https://www. Fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/ https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/

写起来稍微冗长一些:using Index = NamedType<int, struct IndexTag, Comparable, ImplicitlyConvertibleTo<int>>;

当你构建这个时,你需要写一些类似的东西Index{0}但是,当您将其用作索引时,它应该自动转换为基础类型。

它有几个优点,包括能够处理任何类型。最大的缺点是它是您必须导入的外部库而不是内置功能。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

类与枚举类作为索引类型 的相关文章

随机推荐