c++ - 智能指针实现的隐式转换

标签 c++ memory memory-management smart-pointers

我正在尝试实现一个用于教育目的的智能指针类。当 U 类是 T 类的基础时,我希望能够执行以下操作。

ptr<T> t;
ptr<U> u = t; 

我正在努力实现这个隐式转换,所以有人可以帮助我吗?

最佳答案

这是一个使用 std::is_base_of 的例子实现这一目标。

example.h :

#include <type_traits>

template <typename T>
class Example {
public:
  template <
    typename T2,
    typename = typename std::enable_if<std::is_base_of<T, T2>::value>::type
  >
  Example (const Example<T2> &) {}

  Example () = default;
};

正如预期的那样,以下程序编译成功:

#include <example.h>

class Foo {};
class Bar : public Foo {};

int main (int argc, char * argv []) {
  Example<Bar> bar;
  Example<Foo> foo = bar;
}

Bar派生自类 Foo , 所以 Example<Foo>可以从 Example<Bar> 初始化.

同样如预期的那样,以下程序编译失败:

#include <example.h>

class Foo {};
class Baz {};

int main (int argc, char * argv []) {
  Example<Baz> baz;
  Example<Foo> foo = baz;
}

Baz与类无关 Foo , 所以 Example<Foo>无法从 Example<Baz> 初始化. Clang 提供以下错误消息:error: no viable conversion from 'Example<Baz>' to 'Example<Foo>' .

关于c++ - 智能指针实现的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37232273/

相关文章:

C++:请求超过2GB的内存

linux - 为什么不建议将 THP(透明大页面)用于 Oracle 和 MongoDB 等数据库?

c++ - 解码哈夫曼树

c# 字符串到非托管 c++ dll

performance - 当我关闭 {$IMPORTEDDATA} 时,性能是否有真正的提升?

iphone - 一段时间后应用程序用户界面消失

java - 对于偏移量/计数,每个字符串实例 "waste"8 个字节是否有意义?

c++ - 如何声明结构类型的 vector ?

c++ - 无法打开文件 libboost_thread_vc-100-mt-gd-1_48.lib

c# - 记录和恢复应用程序状态以快速启动 .NET 应用程序