我有模板类节点,为了遵循copy-and-swap惯用语,我尝试编写swap
函数friend
类Node
我的代码是:
Node.h
#ifndef NODE_H
#define NODE_H
#include<memory>
template<typename type>
class Node
{
type data_;
std::unique_ptr<Node> next_;
public:
Node(type data);
Node(const Node& other);
Node& operator=(Node other);
friend void swap(Node& lhs, Node& rhs);
};
#include "Node.tpp"
#endif
和Node.tpp
template<typename type>
Node<type>::Node(type data):data_(data),next_(nullptr){
}
template<typename type>
Node<type>::Node(const Node& other)
{
data_ = other.data_;
next_ = nullptr;
if(other.next_ != nullptr)
{
next_.reset(new Node(other.next_->data_));
}
}
template<typename type>
void swap(Node<type>& lhs, Node<type>& rhs)
{
using std::swap;
swap(lhs.data_,rhs.data_);
swap(lhs.next_,rhs.next_);
}
template<typename type>
Node<type>& Node<type>::operator=(Node other)
{
swap(*this,other);
return *this;
}
当我从Source.cpp
#include "Node.h"
int main()
{
Node<int> n(3);
Node<int> n2(n);
Node<int> n3(5);
n3 = n2;
}
我收到以下链接错误:
LNK2019: unresolved external symbol "void __cdecl swap(class Node<int> &,class Node<int> &)
答案 0 :(得分:1)
友元声明不会“继承”模板参数,但需要自己的:
template<typename type>
class Node
{
// ...
public:
// ...
template<typename U> // <<<<<<<<<<<
friend void swap(Node<U>& lhs, Node<U>& rhs);
// ^^^ ^^^
// ...
};