tags:

views:

98

answers:

3
+3  Q: 

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 failure };
};

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();
+1  A: 

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;
VJo
Yes that is a pleasant side effect of this pattern, such an error would be equivalent to "cannot instantiate abstract class" with vanilla classes.
Dave Tapley
@Dave Tapley - yes, it depends what you want. Compile or run-time error.
VJo
A: 

This is called template specialization. In this case it is explicit (aka full) specialization, which is recognized by template <>, as opposed to partial specialization.

usta
Correct, however I am interested in the pattern obtained when using an `enum` for the template parameter, and providing full specialisation for each value of the `enum`.
Dave Tapley
@Dave Tapley: Never have come across a specific name for that, interesting if others have...
usta
+3  A: 

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).

sbi