Вопрос

This code compiles without any issue if test is not called so I conclude that c++ allows to create class and function with the same name:

class test {};
void test() {}

int main() {
  test an_instance_of_test;
}

error is:

<stdin>: In function 'int main()':
<stdin>:5:8: error: expected ';' before 'an_instance_of_test'
<stdin>:5:27: warning: statement is a reference, not call, to function 'test' [-Waddress]

And I know that I should not create such unambiguity in the first place but nevertheless this may be experienced in someones else code and I'm asking if there is a way out of this without changing function or class definition.

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

Решение

You should use an elaborated type specifier:

class test an_instance_of_test;

As the standard says (§3.4.4):

An elaborated-type-specifier (7.1.6.3) may be used to refer to a previously declared class-name or enum-name even though the name has been hidden by a non-type declaration.

The name lookup simply ignores any names of non-types:

the identifier is looked up according to 3.4.1 but ignoring any non-type names that have been declared.

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