【问题标题】:g++ typedef templates in inheritor class继承者类中的g ++ typedef模板
【发布时间】:2010-10-13 21:03:03
【问题描述】:

我们可以考虑简化我的问题:

template <class T>
class Base{
    typedef typename std::pair<T, T> pair;
};

template <class T>
class Inheritor : public Base<T> {
    pair *p;                          
    // mean that we want to use constructor of std::pair.
    // say: std::pair withou argument list

    Inheritor<T>::pair *p;
    // dont see his typename
    // say: pair does not name a type

    typename pair *p;
    // I was sure that it works.
    // I dont know why it doesnt work.
    // say: expected nested-name-specifier before 'pair

    typename Inheritor<T>::pair *p;
    // ok!
};

为什么我们不能写类型名对 *p ?我不明白继承者的原因::!它使代码更复杂,更难阅读!

PS (当然是公开的。正如我所说的“简化我的问题......”)

typedef typename Base<T>::pair pair;

在我看来,这是一个……很难翻译的俄语单词("костыль")

它看起来像 Kludge、胶带或 hack =)

据我了解:

typedefs 像往常一样继承函数或变量。 但它无法访问(!!!)。 要访问它,我们应该写

typedef typename Base<T>::pair pair;

typedef typename Inheritor<T>::pair pair;

看起来很有趣Hindu code,但我们需要它! (>_

当然在公共范围内

【问题讨论】:

    标签: c++ templates inheritance typedef


    【解决方案1】:

    当类型名称依赖于模板参数时,它是一个依赖名称You have to use typename to indicate you're naming a type. 阅读那篇文章,你会发现你使用 typename 没有任何意义,除了最后一种情况。

    你的代码应该是这样的:

    template <class T>
    class Base
    {
    public: // you probably don't want a private typedef
        typedef std::pair<T, T> pair; // typename isn't needed here, this isn't dependent
    };
    
    template <class T>
    class Inheritor : public Base<T>
    {
    public: // public again
        typedef typename Base<T>::pair pair; // get the Base's pair type, typedef it
    
        pair *p; // ah, easy to use
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-23
      相关资源
      最近更新 更多