jpo38 jpo38 - 11 months ago 66
C++ Question

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

We have an algorithm library doing lots of

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

Our code is compiled both with VS2015 and g++. We have a common header file included by all our source files (through
option for VS2015 and
for g++). Is there any piece of code/pragma that could be put here to make any cpp file using
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.

Answer Source

I don't think making standard library functions unavailable is the correct approach. First off, NaN are a fundamental aspect of how floating point value work. You'd need to disable all kinds of other things, e.g., sort(), lower_bound(), etc. Also, programmers are paid for being creative and I doubt that any programmer reaching for std::max() would hesitate to use a < b? b: a if std::max(a, b) doesn't work.

Also, you clearly don't want to disable std::max() or std::min() for types which don't have NaN, e.g., integers or strings. So, you'd need a somewhat controlled approach.

There is no portable way to disable any of the standard library algorithms in namespace std. You could hack it by providing suitable deleted overloads to locate uses of these algorithms, e.g.:

namespace std {
    float       max(float, float) = delete;             // **NOT** portable
    double      max(double, double) = delete;           // **NOT** portable
    long double max(long double, long double) = delete; // **NOT** portable
    // likewise and also not portable for min