简体   繁体   English

如何在 class 内声明一个模板的朋友 function 并在 ZA2F221ED4F8EBC29DCBDC4 外部实现这个朋友 function

[英]How to declare a friend function of a template inside a class and implement this friend function ouside class?

Well, I'm trying to implement the copy_and_swap idiom on my first Stack in C++, for that I need to create a swap function and this swap function needs to be a friend function, I tried to do it by this way: Well, I'm trying to implement the copy_and_swap idiom on my first Stack in C++, for that I need to create a swap function and this swap function needs to be a friend function, I tried to do it by this way:

template <class T>
class Stack {
    private:
        int top;
        T* a;
        int MAX;

    public:
        Stack(int MAX);
        Stack(Stack<T>& s);
        bool push(T x);
        bool pop();
        T peek();
        bool isEmpty();
        friend void swap(Stack<T>& f, Stack<T>& s);
        ~Stack();
};

template <class T>
void Stack<T>::swap(Stack<T>& f, Stack<T>& s){
//I will put something where yet.
}

But, the VSCode says this about the swap function: class model "Stack " does not have a "swap" member (I translate for English, my VSCode runs in Portuguese).但是,VSCode 说关于交换 function: class model “堆栈”没有“交换”成员(我用葡萄牙语翻译成英语)。

How I can do that without receiving this error?我怎么能在不收到此错误的情况下做到这一点?

Your friend function is not template, so to define outside, you would have to define the non template function for each type (which seems impracticable):您的朋友 function 不是模板,因此要在外部定义,您必须为每种类型定义非模板 function(这似乎不切实际):

void swap(Stack<int>& lhs, Stack<int>& rhs){/*..*/}
void swap(Stack<char>& lhs, Stack<char>& rhs){/*..*/}
void swap(Stack<MyType>& lhs, Stack<MyType>& rhs){/*..*/}

Simpler (and better IMO) is to define inside the class.更简单(更好的 IMO)是在 class 内部定义。

template <class T>
class Stack {
// ...
    friend void swap(Stack& lhs, Stack& rhs) { /*..*/ };
};

Alternative is to make the friend function template:另一种方法是交朋友 function 模板:

template <class T> class Stack;
template <class T> void swap(Stack<T>&, Stack<T>&);

template <class T>
class Stack {
// ...
    friend void swap<>(Stack& f, Stack& s); // Only the specialization is friend
};

template <class T>
void swap(Stack<T>& lhs, Stack<T>& rhs){ /**/ }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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