我發生了以下模式,並想知道是否有名稱?枚舉類
的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