gpt4 book ai didi

c++ - 使用 CRTP 的模板中的继承类型

转载 作者:搜寻专家 更新时间:2023-10-31 01:37:21 26 4
gpt4 key购买 nike

下面是 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 不需要?

最佳答案

struct B是具体类,不是模板,它的定义不依赖于任何参数。因此,当编译器从 A<B> 继承它时, 它实例化类 A<B>来自模板 A , 见 collection_type 的定义在里面很开心。

struct C是模板,所以 A<C<__T>>取决于参数 __T . A可以专门化,所以编译器不知道什么 collection_type实际上是,或者即使它存在或不存在。所以,我们必须告诉编译器在哪里寻找collection_type。 (因此,A<C<__T>>::collection_type),并且它是一种类型(因此,typename A<C<__T>>::collection_type)。

关于c++ - 使用 CRTP 的模板中的继承类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34265157/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com