【问题标题】:template class inheritance problem模板类继承问题
【发布时间】:2011-05-17 09:19:41
【问题描述】:

你能告诉我,我错过了什么吗?

template <class T> struct Base
{
    T data;
    Base(const T &_data):data(_data) { }
};

template <class T> struct Derived : Base<T>
{
    Derived():Base(T()) {} //error: class 'Derived<T>' does not have any field named 'Base'
};

【问题讨论】:

  • 正如其他人指出的那样,如果您将Base(T()) 更改为Base&lt;T&gt;(T()),它就会编译。但是谁能告诉我们这两个编译器中哪一个是正确的?

标签: c++ templates visual-c++ inheritance gcc


【解决方案1】:
template <class T> struct Derived : Base<T>
{
    Derived():Base<T>(T()) {} 
};

【讨论】:

  • 一个很好的帮助是基 typedef Base&lt;T&gt; Super 的 typedef。 :) 当您在基础中有多个模板参数时,会有很大帮助。
【解决方案2】:

还有一个问题:谁是对的?海合会就在这里。非限定名称查找不查找依赖的基类,因此不会在Base&lt;T&gt; 的范围内找到Base。您也可以将代码更改为以下符合标准的变体

Derived():Derived::Base(T()) {}

如果我没记错的话,这只是 GCC4.5 支持的。早期版本没有正确实现注入的类名查找。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多