Вопрос

Is it correct to do this? :

namespace name {
    int name;
}

void proc(int name)
{
    name::name = name;
}

int main()
{
    int name = name::name;   
    return 0;
}

It works in GCC. But is this OK with standard and other compilers?

Это было полезно?

Решение

Yes this is okay, we need to look at how the scope resolution operator works in this context. If we look at the draft C++ standard section 3.4.3 Qualified name lookup actually has a very similar example, it says (emphasis mine):

If a :: scope resolution operator in a nested-name-specifier is not preceded by a decltype-specifier, lookup of the name preceding that :: considers only namespaces, types, and templates whose specializations are types. If the name found does not designate a namespace or a class, enumeration, or dependent type, the program is ill-formed.[ Example:

class A {
public:
    static int n;
};

int main() {
    int A;
    A::n = 42; // OK
    A b; // ill-formed: A does not name a type
}

—end example ]

Другие советы

Yes, it is perfectly fine to do that. Namespaces are literally designed to resolve this kind of issue once the size of the code/project grows larger.

Here is a good place to check things out about C++.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top