Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding non-member functions in header files

Tags:

c++

templates

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...

like image 730
xcrypt Avatar asked Dec 09 '22 03:12

xcrypt


2 Answers

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.

like image 61
Puppy Avatar answered Dec 27 '22 16:12

Puppy


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.

like image 28
CB Bailey Avatar answered Dec 27 '22 16:12

CB Bailey