Created
October 26, 2018 18:02
-
-
Save davidji/de22e97795b8e17182ed167b6032ce9d to your computer and use it in GitHub Desktop.
This just shows how you can specify traits for enumeration values, including types.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
This is a rather contrived example where one option | |
expressed as an enum leads to a second set of options | |
that's different for each initial option. | |
What I really have in mind is configuration of a peripheral on microcontroller. | |
E.g. you first choose serial port 1, and then that gives you some options for | |
the TX and RX pins which are specific to serial port 1. | |
*/ | |
// The enum for the primary option | |
enum class Options { A, B }; | |
enum class OptionASubOptions { A1, A2 }; | |
enum class OptionBSubOptions { B1, B2 }; | |
// The default will just cause compilation failure since the sub_option_type isn't defined | |
template<Options E> | |
struct option_traits { }; | |
// Specialise for option A | |
template<> | |
struct option_traits<Options::A> { | |
typedef OptionASubOptions sub_option_type; | |
}; | |
// Specialise for option B | |
template<> | |
struct option_traits<Options::B> { | |
typedef OptionBSubOptions sub_option_type; | |
}; | |
template<Options Option> | |
class Foo { | |
public: | |
// The compiler can't work out option_traits<Option>::sub_option_type is | |
// a typename, so we need to tell it explicitely that it is | |
typedef typename option_traits<Option>::sub_option_type sub_option_type; | |
void choose(sub_option_type sub) { | |
// Don't do anything - the point is just to show we can compile an example | |
} | |
}; | |
int main(void) { | |
// Choose option A: | |
Foo<Options::A> foo; | |
// Choose sub-option A1 | |
foo.choose(OptionASubOptions::A2); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment