Restrict functions to namespace


Keywords:c++ 


Question: 

I am building some sort of a neural network library. As I have never built any libraries before, I have some questions concerning the style.
In my project there are for example following classes:

NeuralNetwork, Layer, Util

all in one namespace. Now, Layer and Util need to have some public functions as they will be called in NeuralNetwork. But since NeuralNetwork is the only class that should be accessible for 'the rest of the world' (and btw. it doesn't make any sense to create a single Layer object).

So is there some way I could only use those functions in other classes in that namespace? Or is there a more elegant approach? I thought of extending the class and making only private functions but that wouldn't make any sense and would make the code uglier as the main class does not derive from the others but rather makes use of them.


1 Answer: 

It sounds like you're looking for the anonymous namespace. A bit weird name, I admit.

Basically, in the following code, foo is only available to the rest of the .cpp file:

namespace {
  class Foo { public: Foo(int) {} } ; 
}

Behind the scenes, the compiler will create a unique name, something that cannot clash with any other namespace - not even the anonymous namespaces of other libraries! You don't care about that hidden name. In your .cpp file, you can just use Foo directly.