从两个枚举类创建复合类型,准备好STL映射 [英] Creating a composite type from two enum classes, ready for STL map

查看:248
本文介绍了从两个枚举类创建复合类型,准备好STL映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要从两个枚举类中创建一个复合类型。

I would like to create a composite type out of two enum classes.

enum class Color {RED, GREEN, BLUE};
enum class Shape {SQUARE, CIRCLE, TRIANGLE};

class Object {
  Color color;
  Shape shape;
public:
};

为了在STL中使用 Object container like std :: map<> 我需要重载less-than操作符。然而,为了将两个枚举类变成一个线性索引,我需要枚举类的元素数量(NoE):

In order to use Object in an STL container like std::map<> I would need to overload the less-than operator. However, in order to flatten both enum classes into one linear index I somehow need the number of elements (NoE) of the enum classes:

friend bool operator< (const Object &lhs, const Object &rhs) {
  return NoE(Shape)*lhs.color+lhs.shape < NoE(Shape)*rhs.color+rhs.shape;
}

如果不输入相同的信息两个地方在节目中以一种很好的方式? (好的方式意味着没有 FIRST_ELEMENT,LAST_ELEMENT ,预处理魔法等)

How can this be done without entering the same information (number of elements) in two places in the program in a nice way? (Nice way means no FIRST_ELEMENT, LAST_ELEMENT, preprocessor magic, etc.)

问题(枚举中的元素数量)类似,但不涉及枚举类

Question (Number of elements in an enum) is similar but does not address enum classes.

我想知道什么是在C ++ 11中实现这种类型的复合类型的最好方法。是枚举类定义足够强还是有必要说:?

I would like to know what is the best way to implement this kind of composite types in C++11. Is the enum class definition strong enough, or is it necessary to say:?

enum class Color {RED=0, GREEN=1, BLUE=2};
enum class Shape {SQUARE=0, CIRCLE=1, TRIANGLE=2};


推荐答案

如其他人所说,到运算符中的形状颜色比较其他如果第一个相等。
使用执行运算符的替代方法 std :: tie

As commented and as already stated by others, give precedence to either Shape or Color in the operator< and only compare the other if the first is equal. An alternative implementation for operator< using std::tie:

#include <tuple>
friend bool operator<(const Object& lhs, const Object& rhs)
{
    return std::tie(lhs.color, lhs.shape) < std::tie(rhs.color, rhs.shape);
}

这篇关于从两个枚举类创建复合类型,准备好STL映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆