我发生了以下模式,并想知道是否有名称?枚举类
的enum
定义具体的类:
enum Fruits{ eApple, eBanana };
而一个模板struct
提供了接口:
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();
我觉得这个部分没用:“我们可以这样实现具体的类:”。具体的类是使用'SomeFruit < eApple>苹果;' – Andrey 2010-10-22 13:08:51
实现的为什么不只是做一个'Apple'和'Banana'类? – GManNickG 2010-10-22 13:12:59
@Andrey:注意,没有那部分调用'apple.eatIt()'会导致'assert failure',而不是'吃苹果'。 – dukedave 2010-10-22 14:26:11