代码之家  ›  专栏  ›  技术社区  ›  Andrey Pro

无法从模板基类导入typedef

  •  1
  • Andrey Pro  · 技术社区  · 7 年前

    这个问题不是重复的,而是后续的问题 Propagating 'typedef' from based to derived class for 'template'

    作为继承typedef的解决方案,建议使用 using 将它们导入派生类,而 using typename Base::typedefed_type 应该够了。

    以下代码主要取自 Roman Kruglov's answer

    #include <vector>
    template<typename T>
    class A
    {
    public:
        typedef std::vector<T> Vec_t;
    };
    
    
    template<typename T>
    class B : public A<T>
    {
    public:
        using typename A::Vec_t;
        // .........
    
    private:
        Vec_t v;
    };
    
    int main()
    {
    B<int> bb;
    }
    

    但是它无法编译,因为编译器非常需要 A

    英特尔编译器错误消息:

        1>C:\Work\EDPS\test_eigen\test_eigen.cpp(27): error : argument list for class template "A" is missing
    1>      using typename A::Vec_t;
    1>                     ^
    1>          detected during instantiation of class "B<T> [with T=int]" at line 34
    1>
    1>C:\Work\EDPS\test_eigen\test_eigen.cpp(31): error : identifier "Vec_t" is undefined
    1>      Vec_t v;
    1>      ^
    1>          detected during instantiation of class "B<T> [with T=int]" at line 34
    1>
    

    MVC错误消息:

     c:\work\edps\test_eigen\test_eigen.cpp(27): error C2955: 'A': use of class template requires template argument list
    1>c:\work\edps\test_eigen\test_eigen.cpp(17): note: see declaration of 'A'
    1>c:\work\edps\test_eigen\test_eigen.cpp(32): note: see reference to class template instantiation 'B<T>' being compiled
    1>c:\work\edps\test_eigen\test_eigen.cpp(27): error C3210: 'A': a member using-declaration can only be applied to a base class member
    1>c:\work\edps\test_eigen\test_eigen.cpp(32): warning C4624: 'B<int>': destructor was implicitly defined as deleted
    

    2 回复  |  直到 7 年前
        1
  •  2
  •   Nelfeal    7 年前

    我想混乱是因为 A

    template<typename T>
    struct A {
        using t = T;
    };
    
    template<typename T>
    struct B : A<T> {
        using typename A<T>::t; // Full qualification needed -> mandatory argument list
    };
    
    struct C : A<int> {
        using typename A::t; // Injected class name -> optional argument list
    };
    

    Live on Coliru

    另外,请注意 t 在中提供 C C A<int> 私下里,但你想 T C C 默认情况下公开继承,因为它是 struct

        2
  •  2
  •   CS Pei    7 年前

    把它改成这样

    template<typename T>
    class B : public A<T>
    {
    public:
        using typename A<T>::Vec_t;
        // .........
    
    };
    

    在C++中,如果 A 是一个模板,独立 A. A<T> 解决它。