// 1
// 比如iostream类中的istream和ostream类不可拷贝
// 在父类basic_ios中是这样声明的
// 故意不定义它们意味着假如还是有代码用它们(比如成员函数或者类的友元friend),就会在链接时引发缺少函数定义错误
template <class charT, class traits = char_traits<charT>>
class basic_ios : public ios_base {
public:
private:
basic_ios(const basic_ios& ); // not defined
basic_ios& operator=(const basic_ios&); // not defined
};
// 2 可以用 = delete将函数标记为deleted函数
// deleted函数不能以任何方式被调用,即使你在成员函数或者友元函数里面调用deleted函数也不能通过编译
// deleted函数一般被声明为public而不是private,客户端调用deleted函数先检查可访问性,当遇到private成员时,会出现该函数是private的编译报错
template <class charT, class traits = char_traits<charT>>
class basic_ios : public ios_base {
public:
basic_ios(const basic_ios& ) = delete;
basic_ios& operator=(const basic_ios&) = delete;
};
// 3 deleted 函数过滤重载函数
// C++ 对于含糊的、能被视为数值的类型都能隐式转换为int,但有些调用可能没有意义
bool isLucky(int number);
bool usLucky(char) = delete;
bool usLucky(bool) = delete;
bool usLucky(double) = delete;
// so
isLucky('a'); // wrong
isLucky(11); // right
// 4 禁止部分模板实例化
template<typename T>
void processPtr(T* ptr);
template<>
void processPtr<void>(void*) = delete;
template<>
void processPtr<const void>(const void*) = delete;
template<>
void processPtr<char>(char*) = delete;
template<>
void processPtr<const char>(const char*) = delete;
// 5 类内置模板函数
class Widget {
public:
template<typename T>
void processPtr(T* ptr) {}
private:
template<>
void processPtr<void>(void*); // wrong 模板特例化必须位于一个命名空间作用域,而非类作用域
};
//delete 实现
class Widget {
public:
template<typename T>
void processPtr(T* ptr) {}
};
template<>
void Widget::processPtr<void>(void*) = delete; // public 域,但是已经完成删除