Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

May I declare "using namespace" inside a C++ class?

Tags:

c++

namespaces

Assume having a C++ class. And there's a namespace which should be visible only inside my class. What to do for that?

class SomeClass
{
    using namespace SomeSpace;

public:
    void Method1();
    void Method2();
    void Method3();
};

namespace SomeSpace
{
    /*some code*/
};
like image 677
antpetr89 Avatar asked Feb 15 '12 15:02

antpetr89


2 Answers

using namespace X; is called a using directive and it can appear only in namespace and function scope, but not class scope. So what you're trying to do is not possible in C++. The best you could do is write the using directive in the scope of the namespace of that class, which may not be desirable.

On second thought, though, analyzing your words,

Assume having a C++ class. And there's a namespace which should be visible only inside my class. What to do for that?

I'd suggest something like the following, which I am not sure is what you want.

class A
{
public:
    void Method1();
    void Method2();
    void Method3();
 
private:
 
    class B
    {
       //public static functions here, instead of namespace-scope
       // freestanding functions.
       //these functions will be accessible from class A(and its friends, if any) 
       //because B is private to A
    };

};
like image 198
Armen Tsirunyan Avatar answered Nov 07 '22 22:11

Armen Tsirunyan


No but you can do it like that:

namespace SomeSpace
{
    /*some code*/
};

using namespace SomeSpace;

class SomeClass
{

public:
    void Method1();
    void Method2();
    void Method3();
};

Though it is not recommended either to apply the using namespace directive in header files and often considered as a bad style. It is OK to put in in a source file (.cpp) of your class.

like image 40
Dmitriy Kachko Avatar answered Nov 07 '22 23:11

Dmitriy Kachko