I have a lot of namespace usage in an initialiser list and would like a using namespace to reduce the verbosity. However the initialiser list is outside the scope of the constructor braces so I would have to place the using outside the constructor and pollute the rest of the file with it. Is there a way to scope the using as I want? Rather than:
MyClass::MyClass() :
m_one(nsConstants::ONE),
m_two(nsConstants::TWO),
m_three(nsConstants::THREE)
{}
I want:
MyClass::MyClass() :
using namespace nsConstants;
m_one(ONE),
m_two(TWO),
m_three(THREE)
{}
_
You can't. The standard offers some less good alternatives:
// The stuff you want to use.
namespace foo { namespace bar {
class Frob {};
} }
Now, from least polluting to most polluting.
typedef
makes it possible to write that alias in a private
section of your class definition:
// I)
class Schwarzschild {
typedef foo::bar::Frob FbFrob;
public: Schwarzschild () : a(FbFrob()), b(FbFrob()) {}
private: FbFrob a,b,c;
};
But you can also use it unit-globally, but with an opportunity to rename it:
// II)
class Schwarzschild {
public: Schwarzschild ();
private: foo::bar::Frob a,b,c;
};
// cxx-file
typedef foo::bar::Frob FbFrob;
Scharzschild::Scharzschild() : a(FbFrob()) {}
You can also alias namespaces:
// III)
namespace fb = foo::bar;
class Planck {
public: Planck () : a(fb::Frob()), b(fb::Frob()) {}
private: fb::Frob a,b,c;
};
Or you can cherry pick symbols from other namespaces, with the disadvantage that your Frob
may collide with another Frob
in your unit of translation:
// IV)
using foo::bar::Frob;
class Mach {
public: Mach () : a(Frob()), b(Frob()) {}
private: Frob a,b,c;
};
Just for the sake of completeness, the most polluting solution is using namespace
.
// V)
using namespace foo::bar;
class Newton {
public: Newton () : a(Frob()), b(Frob()) {}
private: Frob a,b,c;
};
Note that III, IV and V can also be limited to your cxx-file, like in the Schwarzschild-example.
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