c++ - Creating a composite type from two enum classes, ready for STL map -
i create composite type out of 2 enum classes
.
enum class color {red, green, blue}; enum class shape {square, circle, triangle}; class object { color color; shape shape; public: };
in order use object
in stl container std::map<>
need overload less-than operator. however, in order flatten both enum classes 1 linear index somehow need number of elements (noe) of enum classes:
friend bool operator< (const object &lhs, const object &rhs) { return noe(shape)*lhs.color+lhs.shape < noe(shape)*rhs.color+rhs.shape; }
how can done without entering same information (number of elements) in 2 places in program in nice way? (nice way means no first_element, last_element
, preprocessor magic, etc.)
question (number of elements in enum) similar not address enum classes
.
i know best way implement kind of composite types in c++11. enum class definition strong enough, or necessary say:?
enum class color {red=0, green=1, blue=2}; enum class shape {square=0, circle=1, triangle=2};
as commented , stated others, give precedence either shape
or color
in operator<
, compare other if first equal. alternative implementation 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); }
Comments
Post a Comment