代码之家  ›  专栏  ›  技术社区  ›  davetapley

枚举类

  •  3
  • davetapley  · 技术社区  · 14 年前

    我偶然发现了下面的图案,想知道它有没有名字?

    一个 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();
    
    3 回复  |  直到 14 年前
        1
  •  3
  •   sbi    14 年前

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

    template< Fruit T >
    struct SomeFruit;
    
    template<>
    struct SomeFruit< eApple > {
        void eatIt() { // eat an apple };
    };
    
    template<>
    struct SomeFruit< eBanana > {
        void eatIt() { // eat a banana };
    };
    

    经常打电话来 编译期多态 运行时多态性 ,在C++中使用虚拟函数实现。

        2
  •  1
  •   BЈовић    14 年前

    我不知道名称,但最好不要实现模板-如果有人试图实例化,只声明模板将引发编译错误:

    template< Fruit T >
    struct SomeFruit;
    
        3
  •  0
  •   usta    14 年前

    这称为模板专门化。在本例中,它是显式(也称为完全)专门化,由 template <> ,而不是部分专业化。