template class friend member

1
2
3
4
5
template<typename T> class Stack
{
public:
friend void swap(Stack&);
}


what is the right syntax to define swap outside the function?
Last edited on
See 'Why do I get linker errors when I use template friends?' in https://isocpp.org/wiki/faq/templates
what does pre-declare mean?
Last edited on
i dont get it


1
2
3
4
5
6
template<typename T> class Stack
{
public:
friend void swap<>(Stack&);
};
template<typename T> void swap(Stack&);

error:

||=== Build: Debug in te (compiler: GNU GCC Compiler) ===|
C:\Users\Lorence\Desktop\te\main.cpp|16|warning: friend declaration 'void swap(Stack<T>&)' declares a non-template function [-Wnon-template-friend]|
C:\Users\Lorence\Desktop\te\main.cpp|16|note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) |
C:\Users\Lorence\Desktop\te\main.cpp|23|error: variable or field 'swap' declared void|
C:\Users\Lorence\Desktop\te\main.cpp|23|error: missing template arguments before '&' token|
C:\Users\Lorence\Desktop\te\main.cpp|23|error: expected primary-expression before ')' token|
C:\Users\Lorence\Desktop\te\main.cpp|24|error: no 'void Stack<T>::swap(Stack<T>&)' member function declared in class 'Stack<T>'|
C:\Users\Lorence\Desktop\te\main.cpp||In function 'int main()':|
C:\Users\Lorence\Desktop\te\main.cpp|96|error: 'class Stack<int>' has no member named 'swap'|

Last edited on
defining it inside the class is easy, but i want to declare outside
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// declare Stack<>
template< typename T > class Stack ;

// declare template function swap
template< typename T > void swap( Stack<T>&, Stack<T>& );

// define Stack<>
template< typename T > class Stack
{
    // ...

    // declare template friend
    friend void swap<> ( Stack<T>&, Stack<T>& );
};

// define template function
template< typename T > void swap( Stack<T>& a, Stack<T>& b ) 
{ 
    // ... 
}

// for good measure, specialise std::swap
// see: http://www.cplusplus.com/forum/general/155730/ 
Last edited on
class Stack<int>' has no member named 'swap'|

why i keep getting this error?

1
2
3
4
Stack<int>first(3);
Stack<int>second(2);

first.swap(second);
Last edited on
swap() is not actually part of the Stack template class, it is only a friend. So, you must use Stack::swap()

EDIT:
Never mind
Last edited on
swap(first, second);
Topic archived. No new replies allowed.