您的位置:首页 > 编程语言 > C语言/C++

Effective C++ : delete和模板成员函数以及模板函数.

2016-04-11 00:00 218 查看
#include <iostream>
#include <type_traits>

template<typename T>
void processPointer(T* ptr) //假如我们不想让该模板函数接受char* 类型的指针这怎么办呢?
{
std::cout<<*ptr<<std::endl;
}

template<>
void processPointer<char>(char*)=delete; //OK,解决了问题.

template<typename T>
class Node{
private:
T key;

public:
template<typename Ty>
Node(const Ty& key_);

~Node()=default;

template<typename Ty, typename Judge = typename std::enable_if< std::is_integral<Ty>::value >::type >
void setKey(Ty* k);

};

template<typename T>
template<typename Ty>
Node<T>::Node(const Ty& key_)
:key(key_)
{
//
}

template<typename T>
template<typename Ty, typename Judge>
void Node<T>::setKey(Ty* k)
{
if(k != nullptr){
this->key = *k;
}
}

int main()
{
int n1 = 10;
char c1 = 'c';
//processPointer(&c1); //error,因为我们已经删除掉了.
processPointer(&n1);

Node<int> node(10);
int* p1 = new int(20);
void* p2 = p1;

node.setKey(p1);
//node.setKey(p2); //error.

node.changeKey(p1);

delete p1;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: