相关疑难解决方法(0)

当Base和Derived都使用派生类型参数进行模板化时调用基础构造函数时出现编译器错误

我很难理解为什么以下代码无法编译:

template <class T>
class Base {
    public:
        Base(int a){}
};
template <class T>
class Derived: public Base<T>  {
    public:
        Derived(int a): Base(a){}
};
int main(){}
Run Code Online (Sandbox Code Playgroud)

在我的编译器(gcc 5.4.0 with C++ 11)上输出错误消息

error: class 'Derived<T>' does not have any field named 'Base'
         Derived(int a): Base(a){}
Run Code Online (Sandbox Code Playgroud)

我看到这有点类似于成员初始化列表错误中的模板基础构造函数调用,尽管该测试用例实际上为我编译而这个不是:主要区别似乎是两者Base并Derived使用相同的类型参数.另外,如果我明确添加类型参数或者为base提供明确的范围,它编译得很好,如

template <class T>
class Base {
    public:
        Base(int a){}
};

template <class T>
class Derived: public Base<T>  {
    public:
        Derived(int a): Derived::Base(a){}
};

int main(){}
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?在注入类名时我是否会误解?

c++ inheritance templates c++11

4
推荐指数
1
解决办法
195
查看次数

模板C++中的范围问题

这个程序有什么范围问题吗?

#include<iostream>

using namespace std;

template<class Type>
class Base
{
   public:
   Type member;
   Base(Type param): member(param){

   }
};

template<class Type>
class Derived: public Base<Type>
{
    public:               
    Derived(Type param):Base<Type>(param){
     //                       ^
     //                       |_______  Not writing Type here gives error, why?
    }
    void display()
    {
        cout << member; /** ERROR HERE **/
    }
};

int main()
{
   Derived<int> p(5);
   p.display();
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

我收到错误'member' was not declared in this scope.如何解决问题?

c++ templates

1
推荐指数
2
解决办法
3078
查看次数

标签 统计

c++ ×2

templates ×2

c++11 ×1

inheritance ×1