我偶然发现了以下模式,想知道它是否有名称?
enum
定义具体类:
enum Fruits{ eApple, eBanana };
模板化的struct
提供接口(interface):
template< Fruit T >
struct SomeFruit {
void eatIt() { // assert failure };
};
然后我们可以这样实现具体的类:
template<>
struct SomeFruit< eApple > {
void eatIt() { // eat an apple };
};
template<>
struct SomeFruit< eBanana > {
void eatIt() { // eat a banana };
};
然后这样使用它们:
SomeFruit< eApple> apple;
apple.eatIt();
最佳答案
通常这样使用(在编译时捕获错误)
template< Fruit T >
struct SomeFruit;
template<>
struct SomeFruit< eApple > {
void eatIt() { // eat an apple };
};
template<>
struct SomeFruit< eBanana > {
void eatIt() { // eat a banana };
};
并且通常称为编译时多态性(与运行时多态性相反,后者在 C++ 中是使用虚函数实现的)。
关于c++ - 枚举类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3997038/