How to override the static method of a template class in a derived class

I have a small problem with redefining the static methods of the basic classes, but the whole question is very complicated and too long (generalization of resource management in the game engine), so here is 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(); }

The above code outputs "bar" in my case, insted I want it to output "baz". How can i do this? It seems that no matter what I try, base :: foo () always calls base :: bar (). I may have a design problem. I have never encountered this problem - how can I solve it?

+8
source share
1 answer

, , ; static virtual.

static , (); , bar virtual bar<int>::foo() derived::bar() derived .

. CURLY Recursive Template Pattern (CRTP) :

#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();
}

+20

Source: https://habr.com/ru/post/1619484/


All Articles