Coding stuff after taking the hint from my previous question's answer, I ran into an issue with overloading Scene::addObject.
To reiterate the relevant bits and make this self contained, with the least details possible:
- I have a hierarchy of objects inheriting from
Interface
of which there areFoo
s andBar
s; - I have a
Scene
which owns these objects; Foo
s are to beunique_ptr
s andBar
s are to beshared_ptr
s in my main (for reasons explained in the previous question);- the
main
passes them to theScene
instance, which takes ownership.
Minimal code example is this:
#include <memory>
#include <utility>
class Interface
{
public:
virtual ~Interface() = 0;
};
inline Interface::~Interface() {}
class Foo : public Interface
{
};
class Bar : public Interface
{
};
class Scene
{
public:
void addObject(std::unique_ptr<Interface> obj);
// void addObject(std::shared_ptr<Interface> obj);
};
void Scene::addObject(std::unique_ptr<Interface> obj)
{
}
//void Scene::addObject(std::shared_ptr<Interface> obj)
//{
//}
int main(int argc, char** argv)
{
auto scn = std::make_unique<Scene>();
auto foo = std::make_unique<Foo>();
scn->addObject(std::move(foo));
// auto bar = std::make_shared<Bar>();
// scn->addObject(bar);
}
Uncommenting the commented lines results in:
error: call of overloaded 'addObject(std::remove_reference<std::unique_ptr<Foo, std::default_delete<Foo> >&>::type)' is ambiguous
scn->addObject(std::move(foo));
^
main.cpp:27:6: note: candidate: 'void Scene::addObject(std::unique_ptr<Interface>)'
void Scene::addObject(std::unique_ptr<Interface> obj)
^~~~~
main.cpp:31:6: note: candidate: 'void Scene::addObject(std::shared_ptr<Interface>)'
void Scene::addObject(std::shared_ptr<Interface> obj)
^~~~~
Uncommenting the shared and commenting the unique stuff also compiles, so I take it the problem is, like the compiler says, in the overload. However I need the overload as both these types will need to be stored in some kind of collection, and they are indeed kept as pointers to base (possibly all moved into shared_ptr
s).
I'm passing both by-value because I want to make clear I'm taking ownership in Scene
(and upping the reference counter for the shared_ptr
s). Not really clear to me where the issue lies at all, and I couldn't find any example of this elsewhere.