How to override static method of template class in derived class

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

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.

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

Live example

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)