views:

253

answers:

2

I understand the troubles you can get into when you put a using declaration inside a header file, so I don't want to do that. Instead I tried to put the using (or a namespace foo =) within the class declaration, to cut down on repetitive typing within the header file. Unfortunately I get compiler errors. Seems like it would be a useful feature.

#ifndef FOO_H
#define FOO_H

// This include defines types in namespace gee::whiz::abc::def,
// such as the class Hello.
#include "file_from_another_namespace.h"

// using namespace gee::whiz::abc::def; // BAD!

namespace x {
   namespace y {
      namespace z {

struct Foo {
    using namespace gee::whiz::abc::def; // Illegal.
    namespace other = gee::whiz::abc::def; // Illegal.

    // Foo(gee::whiz::abc::def::Hello &hello); // annoyingly long-winded

    Foo(other::Hello &hello); // better
    //...
};

} } } // end x::y::z namespace

#endif // FOO_H

In the real code, the namespace names are much longer and annoying and it's not something I can change.

Can anyone explain why this is not legal, or (better) if there's a workaround?

+1  A: 

actually not a totally horrid idea. It makes at least as much sense as how it works now (which granted, isn't much). I think the basic problem is that classes are not the unit of compilation and linking, but 'translation units'. But doing it class by class is much cleaner, having classes be modules, like in Java or C# or other languages that make more sense.

Charles Eli Cheese
+6  A: 

Could you do typedef gee::whiz::abc::def::Hello Hello?

Fredrik Ullner
This will still pollute the namespace which is what he is trying to avoid.
Trent
Not if its being used inside the class declaration.
Georg Fritzsche
Yeah that works! And if I make it a private typedef then other code can't use it accidentally.
Dan
@gf, you're right, if the typedef is inside the class declaration it would work. BTW, I can't change my down-vote to an up-vote even though it was my mistake unless the answer changes :(
Trent
@Trent, I gave it an upvote for you :)
Dan
@Trent: You can always undo a down-vote by clicking the down button again.
jamesdlin
@jamesdlin, no I can't, the message when I try to undo the down-vote or change it to an up-vote is: "Vote too old to be changed, unless this answer is edited". I supposed 'I' could edit the answer, then change my vote :)
Trent