mirror of
https://github.com/aantron/better-enums.git
synced 2025-12-07 17:26:45 +08:00
Added sample with default_ trait.
This commit is contained in:
parent
a444bf349d
commit
2895867224
49
samples/6-traits.cc
Normal file
49
samples/6-traits.cc
Normal file
@ -0,0 +1,49 @@
|
||||
// Using traits to capture project conventions on enums.
|
||||
|
||||
#include <iostream>
|
||||
#include <enum.h>
|
||||
|
||||
// Adopt the convention that the first value in an enum is the default value.
|
||||
template <typename Enum>
|
||||
constexpr const Enum default_()
|
||||
{
|
||||
return Enum::_first;
|
||||
}
|
||||
|
||||
// Make it possible to override the convention for specific enums.
|
||||
#define ENUM_DEFAULT(Enum, Default) \
|
||||
template <> \
|
||||
constexpr const Enum default_<Enum>() \
|
||||
{ \
|
||||
return Enum::Default; \
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Default will be Red, because it is first.
|
||||
ENUM(Channel, int, Red, Green, Blue);
|
||||
|
||||
// Default will be TrueColor, even though it is not first.
|
||||
ENUM(Depth, int, HighColor, TrueColor);
|
||||
ENUM_DEFAULT(Depth, TrueColor);
|
||||
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
// Default construction can now be simulated for some purposes, and the
|
||||
// default value is still declared in one place, not all over the program
|
||||
// code.
|
||||
Depth depth = default_<Depth>();
|
||||
std::cout << depth.to_string() << std::endl;
|
||||
|
||||
std::cout << default_<Channel>().to_string() << std::endl;
|
||||
std::cout << default_<Depth>().to_string() << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Also works at compile-time.
|
||||
constexpr auto value = default_<Channel>();
|
||||
Loading…
x
Reference in New Issue
Block a user