如何在派生类中重写模板类的静态方法 [英] How to override static method of template class in derived class

查看:68
本文介绍了如何在派生类中重写模板类的静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些基本的静态替代静态方法,但是整个问题非常复杂且时间太长(游戏引擎中的资源管理概述),所以这里是一个简化的版本:

I'm having a little issue with overriding static methods of base clases, but the whole question is very complicated and too long (generalization of resource management in game engine), so here's a simplified version:

template<class T>
class base
{
    static void bar()
    { printf("bar"); }
public:
    static void foo()
    { bar(); }
};

class derived : public base<int>
{
    static void bar()
    { printf("baz"); }
};

int main() { derived::foo(); }

在我的情况下,上面的代码输出"bar",说明我希望它输出"baz".我该怎么办?似乎无论我尝试什么,base :: foo()总是调用base :: bar().我的设计可能有问题.我从来没有遇到过这个问题-我该如何解决?

The code above outputs "bar" in my case, insted I want it to output "baz". How can I go about that? It seems that no matter what I attempt, base::foo() always calls base::bar(). I might have an issue with the design. I've never came across this problem - how can I resolve it?

推荐答案

简单的类继承是无法实现的.一个方法不能同时是staticvirtual.

What you're trying to do is not achievable with simple class inheritance; a method cannot be both static and virtual.

您需要一个static方法,以便能够在没有对象(实例)的情况下调用函数;并且您需要barvirtual,以便bar<int>::foo()derived 实例调用时会调用derived::bar().

You need a static method to be able to call a function without an object (an instance); and you need bar to be virtual so that bar<int>::foo() calls derived::bar() when called from a derived instance.

这两个特征是互斥的.但是好奇递归模板模式(CRTP)可能是这里的解决方案:

Those two traits are mutually exclusive. But the Curiously Recursive Template Pattern (CRTP) may be a solution here:

#include <iostream>

template<class T>
struct base
{
    static void foo()
    {
        T::bar();
    }
};

struct derived : public base<derived>
{
    static void bar()
    {
        std::cout << "derived" << std::endl;
    }
};

int main()
{
    derived::foo();
}

实时示例

这篇关于如何在派生类中重写模板类的静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆