c++ - 枚举类

标签 c++ templates

我偶然发现了以下模式,想知道它是否有名称?

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/

相关文章:

c++ - 错误 : mismatched types: <function> and <lambda>

c++ - 用 extern 尝试一些简单的事情

templates - Velocity 模板宏中的闭包

c++ - 自动检测模板函数的返回类型

c++ - 模板、嵌套类和 "expected constructor, destructor, or conversion before ' &' token"

c++ - 计时 STL 容器 - 广泛的变化?

c++ - 为什么在 C++ 中不允许连接两个 const char*?

c++ - Valgrind 合法的 "possibly lost"字节示例

C++ 模板允许丢弃 const 引用限定符

c++ - 如何将重载函数作为模板函数参数传递?