如何解决子类继承基类的问题,同时基类是模板参数

发布于 2025-02-08 17:24:04 字数 984 浏览 1 评论 0原文

#include <iostream>
 using namespace std;
 
 template <typename Child>
 struct Base
 {
     void interface()
     {
         static_cast<Child*>(this)->implementation();
     }
 };
 
 template<typename T,
     template<class T> class Base
 >
 struct Derived : Base<Derived >
 {
     void implementation(T t=0)
     {
          t = 0;
         cerr << "Derived implementation----" << t;
     }
 };



 int main()
 {
     Derived<int,Base<Derived>> d; //Base class as a template parameter is must  
     d.interface();  // Prints "Derived implementation"
 
     return 0;
 }

我希望派生类从模板参数base类继承,同时希望base> base类的实例取决于derived类,派生类有另一个模板参数t,我尝试了多种方法,但无法解决。

基类作为模板参数必须

我已经简化了源代码,但是我描述的这些条件是必要的。

现在,我希望在我描述的这些情况下,我可以称呼interface()成功地

知道有人知道问题在哪里以及如何解决?

#include <iostream>
 using namespace std;
 
 template <typename Child>
 struct Base
 {
     void interface()
     {
         static_cast<Child*>(this)->implementation();
     }
 };
 
 template<typename T,
     template<class T> class Base
 >
 struct Derived : Base<Derived >
 {
     void implementation(T t=0)
     {
          t = 0;
         cerr << "Derived implementation----" << t;
     }
 };



 int main()
 {
     Derived<int,Base<Derived>> d; //Base class as a template parameter is must  
     d.interface();  // Prints "Derived implementation"
 
     return 0;
 }

I hope Derived class inherits from a template parameter Base class,meanwhile hope the instance of Base class depend on Derived class, the Derived class have another template parameterT,I have tried many ways but can't solve it .

Base class as a template parameter is must

I have simplified the source code, but these conditions I describe are necessary.

Now I hope that under these conditions I describe, I can call the interface() sucessfully

Does anyone know where the problem is and how to fix it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柠檬 2025-02-15 17:24:05
template<typename T, 
        template <typename> typename Base>
struct Derived : Base<Derived<T, Base>>
{
    void implementation(T t=0)
    {
        t = 0;
        cerr << "Derived implementation----" << t;
    }
};

Derived<int, Base> d;
d.interface();  // Prints "Derived implementation"

在线演示

template<typename T, 
        template <typename> typename Base>
struct Derived : Base<Derived<T, Base>>
{
    void implementation(T t=0)
    {
        t = 0;
        cerr << "Derived implementation----" << t;
    }
};

Derived<int, Base> d;
d.interface();  // Prints "Derived implementation"

Online Demo

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文