From 28958672240a7a413d857af2cb26fa7906da43d9 Mon Sep 17 00:00:00 2001 From: Anton Bachin Date: Tue, 5 May 2015 15:33:52 -0400 Subject: [PATCH] Added sample with default_ trait. --- samples/6-traits.cc | 49 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 samples/6-traits.cc diff --git a/samples/6-traits.cc b/samples/6-traits.cc new file mode 100644 index 0000000..6933025 --- /dev/null +++ b/samples/6-traits.cc @@ -0,0 +1,49 @@ +// Using traits to capture project conventions on enums. + +#include +#include + +// Adopt the convention that the first value in an enum is the default value. +template +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_() \ + { \ + 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_(); + std::cout << depth.to_string() << std::endl; + + std::cout << default_().to_string() << std::endl; + std::cout << default_().to_string() << std::endl; + + return 0; +} + + + +// Also works at compile-time. +constexpr auto value = default_();