Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding private constants in an inline namespace header

Tags:

c++

namespaces

I have some inline functions contained within a namespace in a header file and am not currently in a position to move them into a cpp file. Some of these inline functions use magic constants, for example:

// Foo.h namespace Foo {     const int BAR = 1234;      inline void someFunc()     {         // Do something with BAR     } } 

However, I want to make these magic constants private - any ideas how? My first thought was to use an anonymous namespace thus:

// Foo.h namespace Foo {     namespace     {         // 'private' constants here         const int BAR = 1234;     }      inline void someFunc()     {         // Do something with BAR     } } 

However, this doesn't work and Foo::BAR is available to any cpp file that includes Foo.h? Is there a way to do this without creating an implementation cpp file?

like image 842
Rob Avatar asked Jan 17 '10 18:01

Rob


1 Answers

You can't, anonymous namespaces work for the translation unit they are defined in (or included into in your case).
You could consider moving them into a detail namespace to signal to the user that they are internal details:

namespace foo {     namespace detail {         int magic = 42;     }      // ... use detail::magic } 
like image 158
Georg Fritzsche Avatar answered Sep 22 '22 10:09

Georg Fritzsche