Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to ensure that a code only uses names from std, and not the global namespace?

Tags:

c++

When using a header which has a format <cname>, an implementation will put names into std namespace. And it may put names into the global namespace as well, as it is described here:

[ Example: The header <cstdlib> assuredly provides its declarations and definitions within the namespace std. It may also provide these names within the global namespace. [...] — end example ]

Is there a (maybe compiler dependent) way to circumvent/disable this behavior (I'm open to any tricky solution)? I'd like to use names from std only, and I'd like to have an error/warning when using names from the global namespace:

#include <cmath>

double a = cos(0.5); // I'd like to have an error here, because std:: is missing

The reasons:

  • It is hard to write a portable code, if it may use names from the global namespace, as these names may be not available in other compilers. It is much cleaner to use everything from std, and not use the global namespace at all
  • cos(0.5f) does a different thing whether std:: is prefixed or not (float vs double result).
like image 585
geza Avatar asked Nov 06 '22 15:11

geza


1 Answers

Since tricky solutions are fine...

Use a C++ parser, e.g. Clang, and write a tool that parses the header file, collects all the function definitions, and then compares that set against all definitions and calls to global functions.

Of course, it will also pick up cases where someone has defined or called a function with the same name as the standard ones, but you will probably want to avoid that as well anyway.

like image 197
Acorn Avatar answered Jan 22 '23 10:01

Acorn