• ### Announcements

#### Archived

This topic is now archived and is closed to further replies.

# Namespaces and friend functions

## Recommended Posts

Ok, given that I make a lot of data types that I want to use in STL containers, it makes sense for me to write a specialisation of the std::swap function. std::swap gets used a lot when sorting or reordering containers. The default std::swap looks something like this:
void swap(T& t1, T& t2)
{
T temp(t2);
t1 = t2;
t2 = temp;
} 

##### Share on other sites
What a good question. In you cpp file where you define swap
can you just do void std::swap(... ?

##### Share on other sites
No. If I do that, then it says that ''swap is not a member of std''. If I then #include something like <algorithm> to convince it of this fact, it says "''swap'' : unable to resolve function overload". And that''s without even getting as far as deciding whether it can access private members or not.

##### Share on other sites
As it happens, I got around my own problem by defining a public member function called swap, and had the std::swap call that one. This seems to be what is needed. But it doesn''t solve the original problem as such (if it is even solvable), being the friend/namespace conflict.

##### Share on other sites
If you want a specialization of swap, I think you are doing it the wrong way.

  // In Header.h - Class header#pragma once#include class C{ // THIS DOES NOT COMPILE WITH VC++ 6 template friend void std::swap(T &, T &);public: C() {} ~C() {}private: void F() {};};namespace std{ template <> void swap( C &c, C &d ) { c.F(); // call private function }}

Provide a full specialization of std::swap. This doesn't not compile with VC++ 6 because there are some problems with friend templates with VC, but I think the syntax should be correct

I'm at work now and have no access to other compilers, I will check later when I get home.

Edited by - void on July 29, 2001 11:57:19 PM

##### Share on other sites
Keep in mind the reason that swap works the way it does is to remain exception-safe. At no point during the swap should any objects be in an inconsistant state should an exception occur. I don''t know what your particular efficiency improvement is, but just take care that it doesn''t compromise safety. Once you start down the dark path, forever will it dominate your destiny.

##### Share on other sites
Checked it with g++ 2.95. It compiles fine.

However, I should also let you know it is generally not advisable to add things to the std namespace. But if you got a good reason, go ahead.

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627681
• Total Posts
2978611

• 13
• 12
• 10
• 12
• 22