当使用std::shared_ptr<>
时可以从 shared_ptr<T>
进行转换至shared_ptr<U>
如果 U 是 T 的基数。
我正在尝试实现同样的目标,我有一个包装指针的模板类,并且我希望进行相同的派生到基类转换,这是如何完成的?
最佳答案
这可以通过以下两种方式中的一种来完成:
- 转换构造函数
- 转换运算符
示例:
template <typename T>
class MyClass {
public:
// converting constructor
template <typename U>
explicit MyClass(MyClass<U> const& other);
// converting operator
template <typename U>
explicit operator MyClass<U>() const; // explicit here is C++11 only
};
如果您同时执行这两项操作,则不幸的是您的转换会不明确。就我个人而言,我发现转换构造函数更容易(并且更惯用),并在我无法修改转换为的类(不是我的代码)时保留转换运算符的使用。
关于c++ - 隐式转换,如shared_ptr<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18041935/