简体   繁体   中英

linking error in friend function of a template class

I have template class node and in order to follow the copy-and-swap idiom i am tryig to write the swap function which is a friend of class Node

my code is :

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

and the 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;
}

when i test it from Source.cpp

#include "Node.h"
int main()
{
    Node<int> n(3);
    Node<int> n2(n);
    Node<int> n3(5);
    n3 = n2;
}

i am getting the following linking error :

LNK2019: unresolved external symbol "void __cdecl swap(class Node<int> &,class Node<int> &)

The friend declaration doesn't "inherit" the template parameter, but needs its own:

template<typename type>
class Node
{
    // ...
public:
    // ...
    template<typename U> // <<<<<<<<<<<
    friend void swap(Node<U>& lhs, Node<U>& rhs);
                      // ^^^           ^^^
    // ...
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM