Enumerated classes
I have happened upon the following pattern, and wondered if there is a name for it?
An enum
defines the concrete classes:
enum Fruits{ eApple, eBanana };
And a templated struct
provides the interface:
template< Fruit T >
struct SomeFruit {
void eatIt() { // assert failur开发者_如何学编程e };
};
We can then implement the concrete classes thus:
template<>
struct SomeFruit< eApple > {
void eatIt() { // eat an apple };
};
template<>
struct SomeFruit< eBanana > {
void eatIt() { // eat a banana };
};
And use them thus:
SomeFruit< eApple> apple;
apple.eatIt();
That's usually used like this (to catch errors at compile-time)
template< Fruit T >
struct SomeFruit;
template<>
struct SomeFruit< eApple > {
void eatIt() { // eat an apple };
};
template<>
struct SomeFruit< eBanana > {
void eatIt() { // eat a banana };
};
and often called compile-time polymorphism (as opposed to run-time polymorphism, which in C++ is achieved using virtual functions).
I don't know the name, but you are better with not implementing the template - just declaring it will throw a compilation error if someone tries to instantiate :
template< Fruit T >
struct SomeFruit;
This is called template specialization. In this case it is explicit (aka full) specialization, which is recognized by template <>
, as opposed to partial specialization.
精彩评论