【问题标题】:Inherited types in templates using CRTP使用 CRTP 在模板中继承类型
【发布时间】:2015-12-14 10:51:20
【问题描述】:

下面是 CRTP 定义自定义集合类型的基本用法:

template <class __B>
struct A
{
    typedef std::vector<__B> collection_type;
};
struct B: public A<B>
{
    collection_type X;
};

在模板中使用

template <typename __T>
struct C: public A<C<__T>>
{
    // collection_type X; <--- this does not compile
    typename A<C<__T>>::collection_type X;
};

为什么 C 需要 "typename ...::" 部分,而 B 不需要?

【问题讨论】:

  • 不合格的查找不查找依赖的基类。并停止命名 __T__B
  • 停止命名事物 __T__B。请参阅 17.6.4.3.2 全局名称 [global.names] >每个包含双下划线 _ 或以下划线后跟大写字母 (2.12) 的名称都保留给实现以供任何使用。

标签: c++ templates inheritance types crtp


【解决方案1】:

struct B是一个具体的类,不是模板,它的定义不依赖于任何参数。因此,当编译器从A&lt;B&gt; 继承它时,它会从模板A 中实例化A&lt;B&gt; 类,在其中看到collection_type 的定义并且很高兴。

struct C 是一个模板,所以A&lt;C&lt;__T&gt;&gt; 依赖于参数__TA 可以被特化,因此编译器不知道collection_type 实际上是什么,或者即使它是否存在。所以,我们必须告诉编译器在哪里寻找collection_type(所以,A&lt;C&lt;__T&gt;&gt;::collection_type),它是一个类型(所以typename A&lt;C&lt;__T&gt;&gt;::collection_type)。

【讨论】:

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