模板友元函数中的链接错误 class
linking error in friend function of a template class
我有模板 class 节点,为了遵循 copy-and-swap 惯用语,我尝试编写 swap
函数,它是 class 的 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> &)
朋友声明没有"inherit"模板参数,但需要自己的:
template<typename type>
class Node
{
// ...
public:
// ...
template<typename U> // <<<<<<<<<<<
friend void swap(Node<U>& lhs, Node<U>& rhs);
// ^^^ ^^^
// ...
};
我有模板 class 节点,为了遵循 copy-and-swap 惯用语,我尝试编写 swap
函数,它是 class 的 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> &)
朋友声明没有"inherit"模板参数,但需要自己的:
template<typename type>
class Node
{
// ...
public:
// ...
template<typename U> // <<<<<<<<<<<
friend void swap(Node<U>& lhs, Node<U>& rhs);
// ^^^ ^^^
// ...
};