代码之家  ›  专栏  ›  技术社区  ›  Steve Townsend

模板基类中枚举的typedef

  •  2
  • Steve Townsend  · 技术社区  · 15 年前

    跟进昨天晚上的答案——我希望更多的评论能回答这个问题,但没有什么风险。

    有没有一种方法可以在不继承的情况下实现这一点,而不需要在下面倒数第二行代码中使用繁琐的代码,该代码将值写入 cout ?

    struct A {
        enum E {
            X, Y, Z
        };
    };
    
    template <class T>
    struct B {
        typedef typename T::E E;
    };
    
    // basically "import" the A::E enum into B.
    int main(void)
    {
        std::cout << B<A>::E::X << std::endl;
        return 0;
    }
    
    2 回复  |  直到 15 年前
        1
  •  2
  •   Cheers and hth. - Alf    15 年前

    唯一的命名方法 enum 直接将值名称继承到类中,方法是从具有这些名称的类继承。

    您显示的代码似乎使用了Microsoft语言扩展。

    在C++ 98中 枚举 typename不能用于限定值名称之一:

    Comeau C/C++ 4.3.10.1 (Oct  6 2008 11:28:09) for ONLINE_EVALUATION_BETA2
    Copyright 1988-2008 Comeau Computing.  All rights reserved.
    MODE:strict errors C++ C++0x_extensions
    
    "ComeauTest.c", line 17: error: name followed by "::" must be a class or namespace
              name... Wild guess: Did you #include the right header?
          std::cout << B<A>::E::X << std::endl;
                             ^
    
    1 error detected in the compilation of "ComeauTest.c".
    

    所以不是……

    typedef typename T::E E;
    

    …做…

    typedef T E;
    

    干杯!

        2
  •  3
  •   Chubsdad    15 年前

    这有帮助吗?

    struct A { 
        enum E { 
            X, Y, Z 
        }; 
    }; 
    
    template <class T> 
    struct B : private T{    // private inheritance.
    public: 
        using T::X; 
    }; 
    
    // basically "import" the A::E enum into B. 
    int main(void) 
    { 
        B<A>::X;             // Simpler now?
        return 0; 
    }