区分模板函数区分裸指针与智能指针
通过特化模板进行区分
template<class T>
struct my_class
{
my_class<T>();
static const bool value = true;
};
template<class T>
struct my_class<T*>
{
my_class<T>();
static const bool value = false;
};
template<class T>
struct my_class<const T*>
{
my_class<T>();
static const bool value = false;
};
template<class T>
void fun(T& a)
{
if (my_class<T>::value)
{
cout << "智能指针" << endl;
}
else
{
cout << "裸指针" << endl;
}
}
int main()
{
int* p = new int(10);
Object* op = new Object(20);
std::shared_ptr<int> ip(new int(30));
fun(p);
fun(op);
fun(ip);
}
也可以通过系统提供的类型萃取
#include<type_traits>
template<class T>
void fun(T& a)
{
if (std::is_class<T>::value)
{
cout << "智能指针" << endl;
}
else
{
cout << "裸指针" << endl;
}
}
int main()
{
int* p = new int(10);
Object* op = new Object(20);
std::shared_ptr<int> ip(new int(30));
fun(p);
fun(op);
fun(ip);
}
对类型不符的对象进行赋值
template<class T>
class Object
{
T data;
public:
Object(const T& a = T()) :data(a) {}
~Object() {}
};
int main()
{
Object<int> iobj(10);
Object<float> fobj(12.23);
iobj = fobj; // 类型不符
}
通过类中添加模板,然后对类型进行强转再进行赋值
template<class T>
class Object
{
private:
T data;
public:
Object(const T& a = T()) :data(a) {}
template<class U>
Object<T> operator=(const Object<U>& obj)
{
if (this != (Object<T>*) & obj)
{
data = (T)obj.Value();
}
return *this;
}
T& Value()
{
return data;
}
const T& Value()const
{
return data;
}
~Object() {}
};
int main()
{
Object<int> iobj(10);
Object<float> fobj(12.23);
iobj = fobj;
}