We have an algorithm library doing lots of std::min
/std::max
operations on numbers that could be NaN. Considering this post: Why does Release/Debug have a different result for std::min?, we realised it's clearly unsafe.
Is there a way to prevent developers from using std::min
/std::max
?
Our code is compiled both with VS2015 and g++. We have a common header file included by all our source files (through /FI
option for VS2015 and -include
for g++). Is there any piece of code/pragma that could be put here to make any cpp file using std::min
or std::max
fail to compile?
By the way, legacy code like STL headers using this function should not be impacted. Only the code we write should be impacted.
The many variations of the min , max , and minmax functions apply to values and initializer lists. These functions need the header <algorithm> . Nearly the same holds for the functions std::move , std::forward and std::swap .
std::max is defined in the header file <algorithm> and is used to find out the largest of the number passed to it. It returns the first of them, if there are more than one.
If you compile using GCC or Clang, you can poison these identifiers.
#pragma GCC poison min max atoi /* etc ... */
Using them will issue a compiler error:
error: attempt to use poisoned "min"
The only problem with this in C++ is you can only poison "identifier tokens", not std::min
and std::max
, so actually also poisons all functions and local variables by the names min
and max
... maybe not quite what you want, but maybe not a problem if you choose Good Descriptive Variable Names™.
If a poisoned identifier appears as part of the expansion of a macro which was defined before the identifier was poisoned, it will not cause an error. This lets you poison an identifier without worrying about system headers defining macros that use it.
For example,
#define strrchr rindex #pragma GCC poison rindex strrchr(some_string, 'h');
will not produce an error.
Read the link for more info, of course.
https://gcc.gnu.org/onlinedocs/gcc-3.3/cpp/Pragmas.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With