Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override static method of template class in derived class

Tags:

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

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?

like image 701
Biser Krustev Avatar asked Dec 11 '15 11:12

Biser Krustev


People also ask

How can you override static method?

Can we override a static method? No, we cannot override static methods because method overriding is based on dynamic binding at runtime and the static methods are bonded using static binding at compile time. So, we cannot override static methods.

Can we override static method in subclass?

The static method is resolved at compile time cannot be overridden by a subclass. An instance method is resolved at runtime can be overridden. A static method can be overloaded.

Is it possible to override static method in C++?

Note that in both C++ and Java, methods cannot be overloaded according to the return type. Can we overload static methods? The answer is 'Yes'.

Can we override static method from parent class?

Static methods are bonded at compile time using static binding. Therefore, we cannot override static methods in Java.


Video Answer


1 Answers

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

like image 87
YSC Avatar answered Sep 28 '22 14:09

YSC