I have two base classes A
, and B
, and a third class C
that (virtually) derives from both of them. Each class exposes its own public shared_ptr
type.
In another class I have two vectors where I want to add objects of type A to one vector, objects of type B to another vector, and objects of type C to both. This results in three add
methods, one for each of those three classes.
My problems arise when I try to further derive from C
:
#include <iostream>
#include <memory>
#include <vector>
class A {
public:
using shared_ptr = std::shared_ptr<A>;
virtual ~A() {};
};
class B {
public:
using shared_ptr = std::shared_ptr<B>;
virtual ~B() {};
};
class C : virtual public A, virtual public B {
public:
using shared_ptr = std::shared_ptr<C>;
virtual ~C() {};
};
class D : virtual public C {
public:
virtual ~D() {};
};
class Test {
protected:
std::vector<A::shared_ptr> vecA;
std::vector<B::shared_ptr> vecB;
public:
void add(const A::shared_ptr& o) {
std::cerr << "in A" << std::endl;
vecA.push_back(o);
}
void add(const B::shared_ptr& o) {
std::cerr << "in B" << std::endl;
vecB.push_back(o);
}
void add(const C::shared_ptr& o) {
std::cerr << "in C" << std::endl;
vecA.push_back(o);
vecB.push_back(o);
}
};
int main()
{
auto a = std::make_shared<A>();
auto b = std::make_shared<B>();
auto c = std::make_shared<C>();
auto d = std::make_shared<D>();
Test t;
t.add(a);
t.add(b);
t.add(c);
t.add(d);
}
This doesn't work - the resolution of which version of add
to call cannot be determined:
test.cc:62:7: error: call to member function 'add' is ambiguous
t.add(d);
~~^~~
test.cc:34:10: note: candidate function
void add(const A::shared_ptr& o) {
^
test.cc:39:10: note: candidate function
void add(const B::shared_ptr& o) {
^
test.cc:44:10: note: candidate function
void add(const C::shared_ptr& o) {
^
I do have the option of simply passing my C
object separately to both Test::add(const A::shared_ptr&)
and Test::add(const B::shared_ptr&)
because in reality the B
version of add
has additional parameters that resolve the overload but I would prefer that the caller not have to remember to do this.
Is this ambiguity resolvable? My target environment constrains me to C++14.
cls::add(const A::shared_ptr& o)
is missing a return type and all aliases are private.