I'm trying to implement a compact way of detecting if a free function is available at compile time (I'm using std::max
as an example). I came up with this:
#include <stdio.h>
#include <algorithm> // (1)
namespace std { struct max; } // (2)
template<typename A>
concept bool have_std_max = requires(A const& a1, A const& a2) {
{ std::max(a1, a2) }
};
template <typename A>
constexpr A const &my_max(A const &a1, A const &a2) {
if constexpr(have_std_max<A>) {
return std::max(a1, a2);
}
else {
return (a1 > a2) ? a1 : a2;
}
}
int main() {
int x = 5, y = 6;
return my_max(x, y);
}
If I comment out (1), the detection works and my code uses the constexpr else branch (see in Compiler Explorer). However, if I comment out both (1) and (2), this code will fail to compile, because the name std::max
is unknown to the compiler. Shouldn't the concept simply return false in this case? Is there a way to implement something similar without having to declare a dummy max
?