Using namespace for initialization list only

I have a lot of use of the namespace in the initializer list, and I would like to use the namespace to reduce verbosity. However, the initializer list goes beyond the curly braces of the constructor, so I would have to use it outside the constructor and pollute the rest of the file. Is there any way to cover usage as I want? Instead:

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) {} 

_

+7
source share
2 answers

You can not. The standard offers several less good alternatives:

 // The stuff you want to use. namespace foo { namespace bar { class Frob {}; } } 

Now from the least polluting to the most polluting .

typedef allows you to write this alias in the 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 singly globally, but with the ability 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 namespace alias:

 // 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 characters from other namespaces, with the disadvantage that your Frob may collide with another Frob in your translation module:

 // IV) using foo::bar::Frob; class Mach { public: Mach () : a(Frob()), b(Frob()) {} private: Frob a,b,c; }; 

Just for 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; }; 

Please note that III, IV and V can also be limited to your cxx file, for example, in the Schwarzschild example.

+4
source

This is clearly impossible. In C ++, there is no such thing as "local use." So you have to stick with the scope operator or use using .

0
source

All Articles