是否可以使用 CRTP 访问 C++ 中的子类型?

如何解决是否可以使用 CRTP 访问 C++ 中的子类型?

我有这个玩具示例,

template <typename TChild>
struct Base {
    template <typename T>
    using Foo = typename TChild::template B<T>;
};

struct Child : Base<Child> {
    template <typename T>
    using B = T;
};


using Bar = Child::Foo<int>;

编译失败。目的是我有一个父类,它提供基于子类成员的类型计算。子类是通过 CRTP 提供的。然而行

using Foo = typename TChild::template B<T>;

编译失败:

<source>: In instantiation of 'struct Base<Child>':
<source>:16:16:   required from here
<source>:13:11: error: invalid use of incomplete type 'struct Child'
   13 |     using Foo = typename TChild::template B<T>;
      |           ^~~
<source>:16:8: note: forward declaration of 'struct Child'
   16 | struct Child : Base<Child> {
      |        ^~~~~

我期待这样的结构起作用是不是太天真了?

https://godbolt.org/z/5Prb84 处的失败代码

解决方法

让我发布另一种方法:

template<typename TChild,class T>
struct GetB {
    using Type = typename TChild::template B<T>;
};

template<typename TChild>
struct Base {
    template<typename T>
    using Foo = typename GetB<TChild,T>::Type;
};

struct Child : Base<Child> {
    template<typename T>
    using B = T;
};

我没有语言律师类型的解释为什么这有效,但它应该与具有额外的间接级别有关。当编译器看到

using Foo = typename TChild::template B<T>;

它可以(并且将会)在此时检查和抱怨使用了不完整的类型。然而,当我们把对 B<T> 的访问包装成一个函数或一个结构体时,

using Foo = typename GetB<TChild,T>::Type;

那么此时我们不会访问 TChild 的内部,我们只是使用它的名称,这很好。

,

CRTP 的问题是派生类在 CRTP 定义中不完整,因此您不能使用其 using

template <typename T>
using Foo = typename TChild::template B<T>;
  • 由于 TChild,需要完整的 :: 类型。
  • TChild 与模板 T 非依赖,因此应进行第一次通过检查(但失败)

您可能会使用外部特征来处理这种情况

template <typename C,typename T>
struct Traits_For_Base
{
    using type = typename C::template B<T>;
};

template <typename TChild>
struct Base {
    template <typename T>
    using Foo = typename Traits_For_Base<TChild,T>::type;
};

Traits_For_Base<TChild,T>T依赖,所以不需要做第一次通过检查。 并且,通过第二次检查(依赖 T),Child 将完成。

Demo

或者您可以更改别名以使其类型依赖于类 Base 的模板参数:

template <typename TChild>
struct Base {
    template <typename T,typename C = TChild,std::enable_if_t<std::is_same_v<C,TChild>,int> = 0> // To avoid hijack
    using Foo = typename C::template B<T>;
};

C依赖模板的,所以不能在第一阶段检查。

Demo

,

以下给出了与要求完全相同的结果。以前的技术不行时,为什么它应该有效,这仍然是一个谜。

#include <type_traits>
#include <string>

template <typename TChild>
struct Base {

    template <typename T>
    static auto foo(){
        return typename TChild::template B<T>();
    }

    template <typename T>
    using Foo = std::decay_t<decltype(foo<T>())>;
};

struct Child : Base<Child> {
    template <typename T>
    using B = T;
};

static_assert(std::is_same<Child::B<int>,int>::value,"");
static_assert(std::is_same<Child::B<std::string>,std::string>::value,"");

https://godbolt.org/z/b6Y5Tb

,

这是否符合您的意思?

#include <type_traits>
template <typename TChild>
struct Base {
    template <typename T>
    static auto constexpr getFoo() {
        return typename TChild::template B<T>{};
    }
};

struct Child : Base<Child> {
    template <typename T>
    using B = T;
};


using Bar = decltype(Child::getFoo<int>());
static_assert(std::is_same_v<Bar,int>);

我基本上用模板静态函数替换了模板别名,该函数返回您希望模板别名编码的类型的默认构造对象,因此 decltype-ing 其结果应该给出您想要的类型。

,

问题在于嵌套模板的实例化需要一个完整的封闭类类型和模板B的声明:

template <typename TChild>
struct Base {

    // TChild should be complete at the moment of this declaration
    // template B should be declared at this moment.
    template <typename T>
    using Foo = typename TChild::template B<T>;
};

Base 的实例化

struct Child : Base<Child>   
/*  TChild = Child at this moment is incomplete */
{
    template <typename T>
    using B = T;
    /* Point where template B begins to exist */
}; /* point where Child is complete */

这些规则是由语言设计的,它们的目标是避免强制编译器在代码中多次来回传递,可能是无限递归,以实际实例化您的意思。弱类型解释器语言通常没有这样的问题,因为它们可以在以后“纠正”自己。

案例 1。 静态函数解决方案之所以有效,是因为没有进行类型声明。您已经声明了一个实际上具有全局作用域的函数模板,但尚未创建具体的函数或类型。

struct Base {
    template <typename T>
    static auto constexpr getFoo() {
        return typename TChild::template B<T>{};
    }
};

struct Child : Base<Child> {
    template <typename T>
    using B = T;
    /* At this point we can instantiate Child::getFoo<int>()*/
}; /* Child is complete now */

此时可以实例化 Child::getFoo<T>,但它只需要函数的返回类型。

using Bar = decltype(Child::getFoo<int>());

您可以将此声明置于声明 Child 之后的 B 中,因为此时 B<int> 将是完整的。您仍然无法在 Base

中声明它

案例 2。 您的解决方案声明了另一个模板 Foo,它不会在 Base 内实例化它。此模板不明确依赖于 TChild,但要求 foo() 的原型存在于实例化点。

template <typename TChild>
struct Base {

    template <typename T>
    static auto foo(){
        return typename TChild::template B<T>();
    }

    // Foo is a template 
    template <typename T>
    using Foo = std::decay_t<decltype(foo<T>())>;
};

实例化发生在您会使用 Base::Foo<T> 的地方,而您实际上并未使用。该声明在您的解决方案中是无效的。在 B 声明之后使用它是合法的。您不能在 Base 内或声明 B 之前的任何地方使用它。

现在,如果您实际上需要在 B 中使用 Base 的实例怎么办? trait 类解决方案来了:

案例 3。 Traits 可以是专门用于子类或具体类的模板,这是一种设计选择。 trait 作为 CRTP 基类的基类,是一种混合形式。它的作用是为 CRTP 提供有用的声明。最灵活的特征命名的可能解决方案之一:

template <typename TChild,template<class> typename Trait>
struct Base : public Trait<TChild> {

    // Trait<TChild>:: tells compiler that Foo is dependant on TChild 
    // and is declared in base class Trait. As compiler had reached this
    // point,the substitution was successful and thus Trait is complete
    using Foo = typename Trait<TChild>::template B<int>;

    // Foo is assumed to be a complete type,we can use it here!
    Foo make_foo() { return Foo{}; }
};

// Declaring trait template in this case.
template <typename T> struct ChildTrait;

// And specializing
template <>
struct ChildTrait<struct Child> {
    template <typename T>
    using B = T; 
};

struct Child : Base<Child,ChildTrait> {    
    using Bar = typename Base::Foo;
};

static_assert(std::is_same<Child::B<int>,"");

这里的想法是 Trait<TChild> = ChildTrait<Child> 必须并且可以是 Base 中的一个完整类,否则我们无法从中派生 Base。稍加修改(省略 usingstatic_asserttypename 使用)这将在 C++98 中编译,因为它不需要 decltype。此方法由标准组件的某些实现使用,例如std:: stream 秒。

特征可以描述具体的存储类型、分配器等。重要的是生成的具体类型没有关系,但在 Base 中声明了一个共享接口。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res