Effective C++笔记
Use member function templates to accpet “all compatible types”
成员函数模板(member function template),泛化copy构造函数
对成员函数群进行筛除
#include <iostream>
using namespace std;
class Top {};
class Middle : public Top{};
class Bottom : public Middle {};
//指针可以通过编译
void testPointer()
{
Top *pt1 = new Middle;
Top *pt2 = new Bottom;
const Top* pct2 = pt1;
}
//不能通过编译
#if 0
template<typename T>
class SmartPtr
{
public:
explicit SmartPtr(T* realPtr);
};
void testSmartPointer()
{
SmartPtr<Top> pt1 = SmartPtr<Middle>(new Middle);
SmartPtr<Top> pt2 = SmartPtr<Bottom>(new Bottom);
SmartPtr<const Top> pct2 = pt1;
}
#endif // 0
template<typename T>
class SmartPtr
{
public:
explicit SmartPtr(T* realPtr)
:_helpPtr(realPtr){}
template<typename U>
SmartPtr(const SmartPtr<U>& other)
: _helpPtr(other.get()) {}
T* get() const { return _helpPtr; };
private:
T* _helpPtr;
};
void testSmartPointer()
{
SmartPtr<Top> pt1 = SmartPtr<Middle>(new Middle);
SmartPtr<Top> pt2 = SmartPtr<Bottom>(new Bottom);
SmartPtr<const Top> pct2 = pt1;
}
int main()
{
return 0;
}
shared_ptrs 支持构造,支持赋值操作
类的copy构造和copy assignment操作符需要声明
总结