Home > Net >  How can I extern classes in a namespace?
How can I extern classes in a namespace?

Time:02-16

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:

#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();
    };
}

CodePudding user response:

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.

  • Related