【问题标题】:Get type of template base class获取模板基类的类型
【发布时间】:2013-01-22 20:30:59
【问题描述】:

下一个代码运行良好(这是我的其他问题的过度简化版本,类型更长、更深、模板更多):

template<class C>
struct Base
{};

template<class C>
struct Derived : public Base<C>
{
   Derived() : Base<C>()
   {}
};

但是,如果不“写入”其基类的完整类型,我怎么能调用基类构造函数呢?例如,我尝试过类似的方法:

template<class C>
struct Base
{
   typedef Base base_type;
};

template<class C>
struct Derived : public Base<C>
{
   Derived() : base_type() {}
};

int main()
{
   Derived<void> b;
}

但“base_type”无法识别。 gcc 抛出的消息是:

test3.cpp: In constructor 'Derived<C>::Derived()':
  test3.cpp:100:17: error: class 'Derived<C>' does not have any field
  named 'base_type'

为了解决这个问题,我必须在构造函数中写入Base&lt;C&gt;::base_type,但这会使base_type 本身的存在变得无关紧要。

难道我的省写运动不可能吗?

而且,为什么没有找到构造函数中的base_type,但它工作正常?

int main()
{
   Derived<void>::base_type b;
}

编辑:@Jack Aidley 的评论中,我发现使用简单别名获取基类类型的最佳形式是:

template<typename C> struct Base {};

template<typename C, typename Base>
struct Derived_impl : public Base
{
    Derived_impl() : Base()
    {}
};

template<typename C>
using Derived = Derived_impl<C, Base<C> >;

int main()
{
   Derived<void> b;
}

【问题讨论】:

  • 有什么理由不能做template&lt;class C, class Base&gt; struct Derived : public Base&lt;C&gt;
  • 这似乎是个好主意。谢谢。

标签: c++ templates inheritance


【解决方案1】:

按照标准

在查找模板中使用的名称声明时 定义,通常的查找规则 (3.4.1, 3.4.2) 用于 不依赖的名字。查找依赖于模板的名称 参数被推迟,直到知道实际的模板参数 (14.6.2)。

这意味着,你必须告诉编译器,base_typeBase 类中,它依赖于C。例如,您可以使用:

template<class C>
struct Derived : public Base<C>
{
    using typename Base<C>::base_type;

    Derived() : base_type() {}
};

或者这个

template<class C>
struct Derived : public Base<C>
{
    Derived() : Derived<C>::base_type() {} 

    // or, as you already told, Base<C>::base_type()
};

【讨论】:

    【解决方案2】:

    你总是可以这样做:

    template<class C>
    struct Base
    {
    };
    
    template<class C>
    struct Derived : public Base<C>
    {
       typedef Base<C> base_type;  // define here
    
       Derived() : base_type() {}
    };
    

    如果您将在 Derived... 中引用基本类型是有意义的...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      • 2016-02-23
      • 2023-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多