微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

这是 C++ 中的合法语法吗?以及如何使用 crtp 技巧?

如何解决这是 C++ 中的合法语法吗?以及如何使用 crtp 技巧?

template<template<typename>class Derived>
class Base{
    public:
        void interface(){
             static_cast<Derived&>(*this).something();
        }
};

template<typename T>
class Derived:public Base<Derived> {
    ...
};

Derived 需要一个模板参数,但我只对 Base 中的 Derived 类使用未命名参数。 我可以使用这种语法吗? 我修什么? 如何在 Base 中访问 Derived?


我可以在 base 中使用 dType = typename Derived::type 添加吗?在 gcc 10.2 版中,我遇到了这样的错误

test.cpp: In instantiation of 'class Base<Derived<int> >':
test.cpp:22:7:   required from 'class Derived<int>'
test.cpp:30:24:   required from here
test.cpp:13:9: error: invalid use of incomplete type 'class Derived<int>'
   13 |   using dType = typename derived::Type;
      |         ^~~~~
test.cpp:22:7: note: declaration of 'class Derived<int>'
   22 | class Derived:public Base<Derived<T>>{

我只是在您的代码添加 using dType = Derived::Type。

解决方法

您可以直接在 Derived 内为模板参数指定一个名称:

template<typename Derived>
class Base{
    public:
        void interface(){
             typename Derived::type some_variable;
             static_cast<Derived&>(*this).something();
        }
};

template<typename T>
class Derived:public Base<Derived<T>> {
public
    using type = T;
    ...
};

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