Re: how to generate unique namespaces
On Sep 18, 5:04 am, Ian Collins <ian-n...@hotmail.com> wrote:
er wrote:
here's why i'm trying to do:
header1.hpp
namespace{ struct A{};}
struct B1{ A a; };
header2.hpp
namespace{ struct A{};}
struct B2{ A a; };
*.cpp
#include <libs/testing_namespace/header1.hpp>
#include <libs/testing_namespace/header2.hpp>
header2.hpp|5|error: redefinition of ?struct<unnamed>::A?|
i should expect that because the translation unit includes
both header1 and header 2. so then how can i automatically
generate unique namespaces, one for each of header1 and
header2?
You can't.
For some definition of "unique". Something like:
namespace header1_private { /* ... */ }
is sufficient for a lot of cases. Or for the really paranoid:
corporate_name_division_name_departement_name_header1.
And since nobody has mentionned it: you almost never want an
anonymous namespace in a header. In his case, for example, if
header1.hpp is included in more than one translation unit, he
has undefined behavior, because of a violation of the one
definition rule for B1.
If you must, use a code generator.
Like you do for the include guards?
If you automatically generate unique namespaces, how do you
use them?
As you said, with a code generator:-). As long as everything is
generated by the same code generator, everything is hunky dory.
(This works for include guards because except for the #ifdef and
immediately following #define, you never use the symbol. And
those are automatically inserted by the "code generator" when
you create the file.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34