Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++: How to override method of a specific class with same interface

I have a situation where I need to inherit from two classes with same interface, but to override them separately and I definitely cannot tweak interfaces. See code example below

template<typename T>
struct Foo
{
    virtual ~Foo() = default;
    virtual void foo() = 0;
};

struct Derived : public Foo<int>, public Foo<double>
{
#if 0 // having something like this would be great, but unfortunately it doesn't work
    void Foo<int>::foo() override
    {
        std::cout << "Foo<int>::foo()" << std::endl;
    }

    void Foo<double>::foo() override
    {
        std::cout << "Foo<double>::foo()" << std::endl;
    }
#endif
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can always define intermediate classes that declare their own interfaces:

template<typename T>
struct Foo
{
    virtual ~Foo() = default;
    virtual void foo() = 0;
};

struct ProxyFooInt : public Foo<int>
{
    virtual void fooInt() = 0;
    
    void foo() override
    {
        return fooInt();
    }
};

struct ProxyFooDouble : public Foo<double>
{
    virtual void fooDouble() = 0;
    
    void foo() override
    {
        return fooDouble();
    }
};

struct Derived : public ProxyFooInt, public ProxyFooDouble
{
    void fooInt() override
    {
        std::cout << "Foo<int>::foo()" << std::endl;
    }

    void fooDouble() override
    {
        std::cout << "Foo<double>::foo()" << std::endl;
    }
};

A more advanced solution would be to use CRTP:

template<typename D>
struct CrtpFooInt : public Foo<int>
{
    void foo() override
    {
        return static_cast<D*>(this)->fooInt();
    }
};

template<typename D>
struct CrtpFooDouble : public Foo<double>
{
    void foo() override
    {
        return static_cast<D*>(this)->fooDouble();
    }
};

struct Derived : public CrtpFooInt<Derived>, public CrtpFooDouble<Derived>
{
    void fooInt()
    {
        std::cout << "Foo<int>::foo()" << std::endl;
    }

    void fooDouble()
    {
        std::cout << "Foo<double>::foo()" << std::endl;
    }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading