Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I extern classes in a namespace?

I want to extern classes in a namespace, without defining the entire class again. For example, I have class A:

class A
{
    private:
        int value;
    public:
        A(int value);
        int get_value();
};

and class B:

class B
{
    private:
        int value;
    public:
        B(int value);
        int get_value();
};

But I want to extern the A and B classes, without defining all of them in the namespace again, like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include "a.hpp"
#include "b.hpp"

namespace kc
{
    extern class A;
    extern class B;
}

and I don’t want to do:

namespace kc
{
    class A
    {
        private:
            int value;
        public:
            A(int value);
            int get_value();
    };
    class B
    {
        private:
            int value;
        public:
            B(int value);
            int get_value();
    };
}

>Solution :

If you want to refer to the same classes as though they were members of the namespace, then you can do that with a pair of using declarations.

namespace kc
{
    using ::A;
    using ::B;
};

Note however, that this does not make the classes into members of the namespace, and language features like ADL won’t be affected by it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading