一、模板特化类

普通指针和智能指针的最大区别就是,智能指针是一个对象类型,而普通指针是一个指针类型,通过这一点,我们便可以使用通用模板和特化模板类进行区分,从而达到目的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <memory>
using namespace std;
//普通对象版本
template<class T>
struct mybool
{
static const bool result = true;
};
//指针特化版本
template<class T>
struct mybool<T*>
{
static const bool result = false;
};

//判断是普通指针还是智能指针
template<class _Ty>
void fun(_Ty& value)
{
if (mybool<_Ty>::result == true)
{
cout << "智能指针" << endl;
}
else
{
cout << "普通指针" << endl;
}
}
int main()
{
int* p = NULL;
unique_ptr<int> iptr;
fun(p);
fun(iptr);
return 0;
}

在这里插入图片描述