2010-10-22 104 views
3

我发生了以下模式,并想知道是否有名称?枚举类

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(); 
+0

我觉得这个部分没用:“我们可以这样实现具体的类:”。具体的类是使用'SomeFruit < eApple>苹果;' – Andrey 2010-10-22 13:08:51

+0

实现的为什么不只是做一个'Apple'和'Banana'类? – GManNickG 2010-10-22 13:12:59

+0

@Andrey:注意,没有那部分调用'apple.eatIt()'会导致'assert failure',而不是'吃苹果'。 – dukedave 2010-10-22 14:26:11

回答

3

这通常使用这样的(捕捉在编译时的错误)

template< Fruit T > 
struct SomeFruit; 

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

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

和通常被称为编译时多态性(相对于运行时多态性,其在C++中使用虚拟功能来实现)。

1

我不知道名字,但你是不执行模板更好 - 只是宣称,如果有人试图实例它会抛出一个编译错误:

template< Fruit T > 
struct SomeFruit; 
+1

是的,这是这种模式的愉快的副作用,这样的错误将等同于“不能实例化抽象类”与香草类。 – dukedave 2010-10-22 14:32:42

+0

@Dave Tapley - 是的,这取决于你想要的。编译或运行时错误。 – 2010-10-22 14:39:15

0

这就是所谓的模板专业化。在这种情况下,它是明确的(又称完整)专业化,template <>认可,而不是部分专业化。

+0

正确,但是我对使用'enum'作为模板参数获得的模式感兴趣,并且为'enum'的每个值提供了完全的专门化。 – dukedave 2010-10-22 14:28:12

+0

@Dave Tapley:从来没有遇到过这样的具体名称,如果其他人有兴趣... – usta 2010-10-22 14:57:58