【问题标题】:"has not been declared" error with inheritance of class templates [duplicate]类模板继承的“尚未声明”错误[重复]
【发布时间】:2020-05-13 13:28:49
【问题描述】:

以下代码:

#include <iostream>

struct A {
    using A_int = int;               // A_int type declared here
    virtual void foo(A_int) = 0;
};

template <typename T>
struct B : public A {

};

template <typename T>
struct C : public B<T> {
    void foo(A_int) override {
        std::cout << "all good\n";
    }
};

int main()
{
  C<int> c;
  c.foo(1);
}

产生这个错误:

15:14: error: 'A_int' has not been declared

不使用模板的相同代码编译得很好。谁能解释一下为什么?

【问题讨论】:

    标签: c++ templates inheritance


    【解决方案1】:

    你需要说出A_int来自哪里:

    void foo(typename B<T>::A_int) override {
        std::cout << "all good\n";
    }
    

    这是demo

    【讨论】:

      【解决方案2】:

      A_int 必须通过类说明符 A:: 访问,所以它变成 A::A_int

      #include <iostream>
      
      struct A {
          using A_int = int; 
          virtual void foo(A_int) = 0;
      };
      
      template <typename T>
      struct B : public A {
      
      };
      
      template <typename T>
      struct C : public B<T> {
          void foo(A::A_int) override {
              std::cout << "all good\n";
          }
      };
      
      
      int main()
      {
        C<int> c;
        c.foo(1);
      }
      

      【讨论】:

      • 如果在我无法修改的文件中声明了 A,我能做些什么吗?
      • 哦,是的,抱歉,您可以使用 A::A_int 访问它
      猜你喜欢
      • 2011-10-27
      • 1970-01-01
      • 2015-06-12
      • 1970-01-01
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-21
      相关资源
      最近更新 更多