Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 枚举类_C++_Templates - Fatal编程技术网

C++ 枚举类

C++ 枚举类,c++,templates,C++,Templates,我偶然发现了下面的模式,想知道它是否有一个名字 enum定义了具体的类: enum Fruits{ eApple, eBanana }; 模板化的结构提供了接口: template< Fruit T > struct SomeFruit { void eatIt() { // assert failure }; }; 模板 构造一些水果{ void eait(){//assert failure}; }; 然后,我们可以实现具体的类,如下所示: template<

我偶然发现了下面的模式,想知道它是否有一个名字

enum
定义了具体的类:

enum Fruits{ eApple, eBanana };
模板化的
结构提供了接口:

template< Fruit T >
struct SomeFruit {
    void eatIt() { // assert failure };
};
模板
构造一些水果{
void eait(){//assert failure};
};
然后,我们可以实现具体的类,如下所示:

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

template<>
struct SomeFruit< eBanana > {
    void eatIt() { // eat a banana };
};
模板
构造一些水果{
void eait(){//吃一个苹果};
};
模板
struct SomeFruit{
void eait(){//吃香蕉};
};
并使用它们:

SomeFruit< eApple> apple;
apple.eatIt();
苹果; 苹果;
我不知道该模板的名称,但最好不要实现该模板-如果有人试图实例化以下内容,仅声明该模板将引发编译错误:

template< Fruit T >
struct SomeFruit;
模板
构造一些果实;

这称为模板专门化。在这种情况下,它是显式(又称完全)专门化,由
模板识别,而不是部分专门化。

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

模板
构造一些果实;
模板
构造一些水果{
void eait(){//吃一个苹果};
};
模板
struct SomeFruit{
void eait(){//吃香蕉};
};

并常称为“强>编译时多态性>(与C++中使用虚拟函数实现的运行时多态性相反)。p> 我认为这部分是无用的:“我们可以这样实现具体的类:”。具体类是使用

SomeFruitapple实现的
为什么不直接创建一个
Apple
Banana
类呢?@Andrey:请注意,如果不调用
Apple.eatIt()
这个部分,将导致
断言失败
,而不是
吃苹果
@Gman:我对这种模式很感兴趣,因为我们对实现
某些水果
的具体类有严格的排序,即它们在
枚举
中出现的顺序。在普通类层次结构中,兄弟级之间不存在这种排序。您是对的,它比我认为的更复杂,但是我对使用
enum
作为模板参数时获得的模式感兴趣,并为
enum
@Dave Tapley的每个值提供完整的专业化:从未遇到过这个值的特定名称,如果其他人有,这很有趣……是的,这是这个模式的一个令人愉快的副作用,这样的错误将相当于“无法实例化抽象类”和普通类。@Dave Tapley-是的,这取决于你想要什么。编译或运行时错误。
template< Fruit T >
struct SomeFruit;

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

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