【发布时间】:2021-05-14 03:37:30
【问题描述】:
我正在尝试实现自定义智能指针。所以我有这样的事情:
// Base class for every object
class Base {
public:
int n_holders {};
};
class Derived : public Base {};
// Custom shared pointer
template<class T>
class Sptr {
public:
T* obj;
Sptr(T* obj_) : obj{obj_} {}
};
void SomeFunc(Sptr<Base> obj) {}
void SomeFunc2(std::shared_ptr<Base> obj) {}
int main()
{
auto a = Sptr<Base>(new Base());
SomeFunc(a); // OK
auto b = Sptr<Derived>(new Derived());
SomeFunc(b); // Error. No matching function call to SomeFunc
auto c = std::shared_ptr<Base>(new Base());
SomeFunc2(c); // OK
auto d = std::shared_ptr<Derived>(new Derived());
SomeFunc2(d); // OK !!!
}
我的问题是,如果使用std::shared_ptr 没有错误,为什么编译器不能自动从Sptr<Derived> 转换为Sptr<Base>?。如何让它成为可能?
【问题讨论】:
标签: c++ templates casting derived-class