Mr. Developerdude
Mr. Developerdude

Reputation: 9688

How to resolve multiple inheritance ambiguities in C++

I have a small program as follows:

#include <iostream>

template <typename T>
class X{
    public:
        bool something(){
            return true;
        }
};

class A: public X<A>{
};


class B: public A, public X<B>{
};


template <typename T>
bool use(T &t)
{
    return t.something();
}



int main()
{
    B b;
    std::cout << "use returned: " << use(b);
}

This will not compile because there is an ambiguity as to which of the two possible versions of something() should be selected:

In instantiation of 'bool use(T&) [with T = B]':
30:43:   required from here
22:20: error: request for member 'something' is ambiguous
6:14: note: candidates are: bool X<T>::something() [with T = B]
6:14: note:                 bool X<T>::something() [with T = A]
 In function 'bool use(T&) [with T = B]':
23:1: warning: control reaches end of non-void function [-Wreturn-type]

My question is, how can I resolve this ambiguity if the only place I can edit is the body of use()?

Upvotes: 2

Views: 567

Answers (2)

bpeikes
bpeikes

Reputation: 3715

You could add a specialization of the template “use” for the case where T derives from X and then casts to X inside.

template <typename T>
class X{
    public:
        bool something(){
            return true;
        }
};

class A: public X<A>{
};


class B: public A, public X<B>{
};

#
# If class derives from X<T> make sure to cast to X<T> before calling something
#
template<typename T>
typename std::enable_if<std::is_base_of<X<T>, T>::value, bool>::type use(T &t)
{
     return static_cast<X<T>&>(t).something();
}

#
# This gets run for everything that doesn't derive from X<T>
#
template<typename T>
typename std::enable_if<!std::is_base_of<X<T>, T>::value, bool>::type use(T &t)
{
     return t.something();
}

Have to check the syntax though, but this should make sure you get it for your special case while allowing anything with only one “something” call.

Upvotes: 1

vitaut
vitaut

Reputation: 55705

Yes. For example, you can qualify the call to something (godbolt):

template <typename T>
bool use(T &t)
{
    return t.A::something();
}

Upvotes: 4

Related Questions