[[nodiscard]] on numeric_limits functions
Would it be welcome to others to add [[nodiscard]] to the static methods on numeric_limits. It would help point out bugs like
if( lhs == std::numeric_limits<T>::min( ) and rhs == T{ -1 } ) {
std::numeric_limits<T>::max( ); /* oops, ignored it */
}
The standard doesn’t specify that they’re [[nodiscard]], so I’m not sure we can just do that...
I thought implementors had freedom here, I can try and find it as it's not in the obvious place [dcl.attr.nodiscard]
The MSVC STL implementation has [[nodiscard]].
I guess the issue is that
#include <limits>
int main() {
std::numeric_limits<int>::max( );
}
doesn't warn with -Wunused But
#include <limits>
int main( ) {
5; // warns
auto a = std::numeric_limits<int>::max( ); // warns
}
does warn.
It's absolutely fine to add [[nodiscard]] in places where the standard doesn't add it. Its only job is it to make the compiler produce a warning, which the standard has no constraints or requirements on. Libc++ has _LIBCPP_NODISCARD_EXT for cases which aren't in the standard.
Ah yeah, that’s true; I guess I just wasn’t sure because it’s a standard attribute, but it also makes sense that it would be fine.
P3122R0 "[[nodiscard]] should be Recommended Practice" suggests to make these things recommended practice. (The author of the paper is the maintainer of libstdc++.) If that gets accepted we probably want to consider adding [[nodiscard]] in more places unconditionally and even removing _LIBCPP_NODISCARD_EXT.
Another interesting tidbit, had the static constexpr function been consteval(non-addressable function anyways) it will warn. But only clang, not gcc/msvc
template<typename>
struct limits;
template<>
struct limits<int> {
static constexpr int foo( ) { return 5; }
static consteval int bar( ) { return 6; }
};
int main() {
limits<int>::foo( ); // no warning
limits<int>::bar( ); // -Wunused-value warning
}