4

I'm wondering if I can define some functions in a header file and then use them in the same header file, while hiding them from anything else?

For example, can I first define some general helper functions(specific to the data-structures), and then define some data-structures in the same header that use those functions?

eg:

template<class T>
void Swap(T &a, T &b)
{
  T temp = a;
  a = b;
  b = temp;
}

But I don't want Swap() to interfere with other functions that have the same name.

I could make it a private method, but then I'd have to provide every class that uses it with the same implementation or make them friend class...

xcrypt
  • 3,276
  • 5
  • 39
  • 63
  • 2
    Concerning Swap interfering with other swap functions, that's why namespaces were invented, use them! As far as I know, you can only hide functions in the header file by making them private inside of a class or a struct. You could make a struct with just this function as a private, and specify the class you're making as a friend class. – leetNightshade Dec 23 '11 at 21:45

2 Answers2

8

Traditionally, the namespace details is used for implementation-reserved stuff that has to go in a header.

Also, there's a std::swap, so no need for your own.

Puppy
  • 144,682
  • 38
  • 256
  • 465
6

You usually can't hide the function completely from other clients but you can put it in its own namespace so that it doesn't interfere with client code. A common practice is to make the namespace an inner namespace of your main library namespace and to call it details or something similar.

Of course, if you need to function to be available through ADL then it has to live in the namespace enclosing the classes for which the ADL is supposed to match. There's no way around this.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656