您的位置:首页 > 其它

Meta: 模板成员函数.

2016-03-27 00:00 155 查看
运用好模板成员函数可以使得当前class具有兼容性:

比如我们定义了一个template-class: Node<T>接着我们实例化出来Node<int> first_(5)和Node<double> second_(0.5),我们想让first_ = second.怎么办呢,这个时候模板成员函数就派上了用场.

我们一般称:模板成员函数为 泛化成员函数.

泛化的成员模板随之也带来两个问题,这要追溯二个性质:

1,就是两个分别实例化的模板是没有联系的。比如Node<int>(5)和Node<int>(6)这两个实例化的结果就像马嘴和牛屁股没有任何联系.

2,泛化构成员函数并不会影响编译器合成自己的拷贝构造函数,移动构造函数,拷贝复制运算符,移动赋值运算符.....因此我们要想获得对当前template-class的精确控制也必须声明定义出来这些函数.

3,构造函数是不需要泛化的!!!!!!!!!!!!!!!!!!!!!!!!!!!!

我们来看一下代码吧:

#include <iostream>

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

public:
Node()=default;

explicit Node(const T& key);  //构造函数.

Node(const Node<T>& other_node_); //普通拷贝构造函数.

template<typename Ty>
Node(const Node<Ty>& other_node_); //泛化拷贝构造函数.

template<typename Ty>
Node(Node<Ty>&& other_node_);  //泛化移动构造函数.

Node(Node<T>&& other_node_); //普通移动构造函数.

Node<T>& operator=(const Node<T>& other_node_); //普通拷贝赋值运算符.

template<typename Ty>
Node<T>& operator=(const Node<Ty>& other_node_); //泛化拷贝复制运算符.

Node<T>& operator=(Node<T>&& other_node_);  //普通移动复制运算符.

template<typename Ty>
Node<T>& operator=(Node<Ty>&& other_node_); //泛化移动赋值运算符.

inline T get()const
{
return this->key_;
}

inline T& get()
{
return this->key_;
}

inline void print()const
{
std::cout<<"key_: "<<this->key_<<std::endl;
}

~Node()=default;
};

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

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

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

template<typename T>
Node<T>::Node(Node<T>&& other_node_)
:key_(std::move(other_node_.key_))
{
//
}

template<typename T>
template<typename Ty>
Node<T>::Node(Node<Ty>&& other_node_)
:key_(std::move(other_node_.get()))
{

}

template<typename T>
Node<T>& Node<T>::operator=(const Node<T>& other_node_)
{
this->key_ = other_node_.key_;
return *this;
}

template<typename T>
template<typename Ty>
Node<T>& Node<T>::operator=(const Node<Ty>& other_node_)  //注意这里的返回类型.
{
this->key_ = other_node_.get();

return *this;
}

template<typename T>
Node<T>& Node<T>::operator=(Node<T>&& other_node_)
{
this->key_ = std::move(other_node_.key_);
return *this;
}

template<typename T>
template<typename Ty>
Node<T>& Node<T>::operator=(Node<Ty>&& other_node_)
{
this->key_ = std::move(other_node_.get());
return *this;
}

int main()
{
//case 1:
Node<int> nodeOne(0.5); //从double 到 int.
nodeOne.print();

//case 2:
Node<int> nodeTwo(20);
Node<double> nodeThree(30.5);
nodeTwo = nodeThree;  //从double 到 int,
nodeTwo.print();

//case 3:
Node<int> nodeFour(Node<double>(4.880));
nodeFour.print();

//case 4:
Node<int> nodeFive(20);
nodeFive = Node<double>(10.11);
nodeFive.print();

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