Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to prevent developers from using std::min, std::max?

Tags:

c++

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.

like image 466
jpo38 Avatar asked Oct 10 '16 07:10

jpo38


People also ask

Is there a max and min Function in c++?

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 .

What is std :: max in C++?

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.


1 Answers

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

like image 181
cat Avatar answered Nov 06 '22 04:11

cat