Mihai
Mihai

Reputation: 1084

Access the corect methods from multiple base classes based on some template parameter and without shadowing them

I have the following sketch

//g++  7.4.0

#include <iostream>

template<int T>
struct X {
    static int type() { return T; };    
};

template<typename T>
struct FooBase {
    int foo() { return T::type(); }
};

struct Foo : public FooBase<X<1>>, public FooBase<X<2>> {
    
    template<int T>
    int foo() { return FooBase<X<T>>::foo(); }
};

int main()
{
    std::cout << "Hello, world!\n";
    
    Foo fobj;
    
    std::cout << fobj.foo<1>() << std::endl;
    std::cout << fobj.foo<2>() << std::endl;
}

This example works, whenever I call fobj.foo<1>() or fobj.foo<2>() the correct foo method from its corresponding base class is called.

My question is if there is a way to get rid of this 'wrapper' method

template<int T>
int foo() { return FooBase<X<T>>::foo(); }

method from the Foo class and access the correct method from the base classes some other way. I am asking this because let's assume that FooBase class has already a lot of methods and I don't like that in class Foo I need to create that wrapper just to call the correct method from the base class.

Upvotes: 1

Views: 31

Answers (1)

florestan
florestan

Reputation: 4655

So here's one way you could do it. As your Foo derives from the bases, you could add the disambiguation one step ahead by adding the following function to Foo:

template<int I>
FooBase<X<I>>& as_base() { return static_cast<FooBase<X<I>>&>(*this); }

The call site would look like

Foo f;
f.as_base<1>().foo();

Still not really beautiful, but at least you'd not have to write delegates for all functions.

See complete example here.

Upvotes: 2

Related Questions