2016-11-26 27 views
4

我有模板類節點,以遵循copy-and-swap成語我是tryig寫swap函數,它是類的friendNode在模板類的友元函數連接錯誤

我的代碼是:

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> &) 

回答

1

friend聲明不 「繼承」 模板參數,但需求它自己:

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

我很抱歉,但可以喲你好好細說一下。我完全不能完全掌握。 – Hummingbird

+0

@Hummingbird現在更清晰? –

+0

是的..非常感謝.. – Hummingbird