Puneet Mittal
Puneet Mittal

Reputation: 542

namespace conflict in c++

I have the following C++ classes.

xyz.h

class xyz {
public:
    static int abc();
};

qwe.h

#include xyz.h

namespace xyz {

class qwe{
public:
    void bnm() {
        int value = xyz::abc();

    }
};

}

How do I access xyz::abc() here. I get a compilation error here saying abc is not a member of xyz. I understand the reason that it's trying to search for the abc method inside this xyz namespace whereas what it should ideally get is a static method in the xyz class.

Is there a way to get around this without changing the namespace names?

Upvotes: 1

Views: 1648

Answers (4)

theorange
theorange

Reputation: 11

namespace hack = xyz;
hack::abc();

Upvotes: 1

Kirill Kobelev
Kirill Kobelev

Reputation: 10557

In your particular case there is no direct solution. Altough C++ has a concept of elaborated type specifier, in particular:

xyz       ab;   // The defn is ambiguous.
class xyz ab;   // The ambiguity is resolved.

You can aslo try this:

class xyz dummy;
int value = dummy.abc();

C++ allows calling static methods using syntax of the instance methods.

Upvotes: 2

Johan Lundberg
Johan Lundberg

Reputation: 27078

In the special case that the file xyz.h is really simple and depend on little else, you can do this:

namespace othername {
   #include "xyz.h"
}

and then use

othername::xyz::abc();

Upvotes: 1

vinnydiehl
vinnydiehl

Reputation: 1704

Don't make a class with the same name as a namespace (or its own namespace for that matter).

Upvotes: 2

Related Questions