|
Boost : |
Subject: [boost] [Better Enums] Maps between enums and other types
From: Anton Bachin (antonbachin_at_[hidden])
Date: 2015-07-11 21:16:31
Hello,
In past exchanges on this list, several people expressed a desire for
bidirectional maps on enums. I've made a simple implementation [1] that relies
on constexpr functions containing a switch. The switch forces case
exhaustiveness checking. This method therefore requires C++14 to be truly
useful.
Usage is:
ENUM(Channel, int, Red, Green, Blue)
constexpr const char* describe(Channel channel)
{
switch(channel) {
case Channel::Red: return "the red channel";
case Channel::Green: return "the green channel";
case Channel::Blue: return "the blue channel";
}
}
constexpr auto descriptions = better_enums::make_map(describe);
int main()
{
std::cout << descriptions.from_enum(Channel::Red) << std::endl;
std::cout << descriptions.to_enum("the green channel") << std::endl;
}
This prints
the red channel
Green
In principle, make_map should enumerate the function by passing every possible
value of Channel, and use the results to build up some lookup data structure. I
am not doing that right now because I haven't found a compile-time data
structure with fast enough generation to be practical.
I suppose with reflective information, there are other ways to check for
exhaustiveness besides using a switch. The implementation is currently
inefficient (it uses a linear scan to do the reverse mapping). There is also no
support for multimaps or partial maps. I could probably support the latter
easily by having the function return an option type. I am not sure multimaps are
a good idea at all. The only point of them would be to do a reverse mapping from
multiple values to the same enum.
Interested to hear any opinions.
Anton
[1] http://aantron.github.io/better-enums/tutorial/Maps.html
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk