Enumerated Classes

I came up with the following pattern and wondered if there was a name for it?

An enumdefines specific classes:

enum Fruits{ eApple, eBanana };

And the template structprovides an interface:

template< Fruit T >
struct SomeFruit {
    void eatIt() { // assert failure };
};

Then we can implement specific classes:

template<>
struct SomeFruit< eApple > {
    void eatIt() { // eat an apple };
};

template<>
struct SomeFruit< eBanana > {
    void eatIt() { // eat a banana };
};

And use them this way:

SomeFruit< eApple> apple;
apple.eatIt();
+3
source share
3 answers

This is commonly 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 is often called compile-time polymorphism (as opposed to run-time polymorphism, which in C ++ is achieved using virtual functions).

+3
source

, - , , - :

template< Fruit T >
struct SomeFruit;
+1

This is called specialized specialization. In this case, this is a clear (aka full) specialization, which is recognized template <>, in contrast to partial specialization.

0
source

Source: https://habr.com/ru/post/1770915/


All Articles