using namespace just for initialiser list

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.


This is clearly not possible. There exists no such thing like a "local using" in C++. So you'll have to stick to the scope operator or use using .

链接地址: http://www.djcxy.com/p/56750.html

上一篇: Java ldap身份验证问题

下一篇: 只为初始化列表使用名称空间