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?
using -declarationsIntroduces a name that is defined elsewhere into the declarative region where this using-declaration appears. using typename (optional) nested-name-specifier unqualified-id ; (until C++17)
Avoid using directives (particularly using namespace std; ), except in specific circumstances. Using declarations are generally considered safe to use inside blocks. Limit their use in the global namespace of a code file, and never use them in the global namespace of a header file.
Syntax: classname objectname1, objectname2, …. ,objectname………… n ; For example, Largest ob1,ob2; //object declaration will create two objects ob1 and ob2 of largest class type.
A using declaration in a definition of a class A allows you to introduce a name of a data member or member function from a base class of A into the scope of A.
In class definition. Using-declaration introduces a member of a base class into the derived class definition, such as to expose a protected member of base as public member of derived. In this case, nested-name-specifier must name a base class of the one being defined.
Using-declarations can be used to introduce namespace members into other namespaces and block scopes, or to introduce base class members into derived class definitions, or to introduce enumerators into namespaces, block, and class scopes (since C++20).
If the using-declaration refers to a constructor of a direct base of the class being defined (e.g. using Base::Base; ), all constructors of that base (ignoring member access) are made visible to overload resolution when initializing the derived class.
Could you do typedef gee::whiz::abc::def::Hello Hello
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With