Home > OS >  Use specialization from base class
Use specialization from base class

Time:04-08

I have a class that inherits from a base class. The derived class has a template method. The base class has a specialized version of this method:

#include <iostream>

class Base {
  public:
    static void print(int i) { std::cout << "Base::print\n"; }
};

class Derived : public Base {
  public:
    static void print(bool b) { std::cout << "Derived::bool_print\n"; }

    template <typename T>
    static void print(T t) { std::cout << "Derived::print\n"; }
    
    void Foo() {
        print(1);
        print(true);
        print("foo");
    }
};

int main()
{
    Derived d;
    d.Foo();

    return 0;
}

The output is:

Derived::print
Derived::bool_print
Derived::print

The desired output is:

Base::print
Derived::bool_print
Derived::print

See code at https://onlinegdb.com/BY2znq8WV

Is there any way to tell Derived::Foo to use the specialization from Base instead of using the unspecialized version define in Derived?

Edit

The above example might be oversimplified as @Erdal Küçük showed. In actuality Derived subclasses from Base using CRTP, so it is not known if Base has a print method. A fuller example can be found at https://onlinegdb.com/N2IKgp0FY

CodePudding user response:

This might help:

class Derived : public Base {
public:
    using Base::print; //one of the many useful usages of the keyword 'using'
    //...
};

See: Using-declaration in class definition

  • Related