I was under the impression that unique_ptr
could infer class hierarchy in the same way that a normal pointer can, but when I try to overload a function like this:
void func(unique_ptr<Derived1>& d1);
void func(unique_ptr<Derived2>& d2);
And then call one of the functions like this:
unique_ptr<Base> b = make_unique<Derived1>();
func(b);
I get an error saying that no instance of overloaded function "func" matches the argument list
. The runtime type of b is Derived1
, so I expected that the first overload would be called.
Also, when I return a unique_ptr
from a function, the compiler is able to cast (? not sure of the appropriate terminology) a derived class to a base class, so that something like this works:
unique_ptr<Base> create(){
return make_unique<Derived1>();
}
Often in my code I have variables declared as the result of functions like this. They're declared as base but have derived runtime types, and I would like to pass them into one single overloaded function.
How do I overload functions in the same way that I would with regular pointers where class hierarchies are involved?
Derived
is (publicly) derived fromBase
, then aDerived *
can be implicitly converted to aBase *
. This means aDerived *
can be implicitly converted to aBase*
, and passed as an argument to a function that accepts aBase *
. However, there is no inheritance relationship between astd::unique_ptr<Base>
and astd::unique_ptr<Derived>
, so astd::unique_ptr<Derived>
cannot be implicitly converted tostd::unique_ptr<Base>
, nor can it be passed as an argument to a function that expects astd::unique_ptr<Base>
. – Rennin