Kaz*_*ade 2 c++ templates casting
当使用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
};
Run Code Online (Sandbox Code Playgroud)
如果您同时执行这两项操作,那么很遗憾,您的转换模糊不清.我个人认为转换构造函数更容易(更惯用)并保留使用转换运算符的情况,当我无法修改转换为类(而不是我的代码).
| 归档时间: |
|
| 查看次数: |
137 次 |
| 最近记录: |