Why does std :: numeric_limits <SomeStruct> :: infinity () "work"?

I accidentally loaded the default initialized struct into std::numeric_limits<somestruct>::infinity() . What I got was the default structure.

Why does the standard allow this to compile and return such an unexpected value?

 #include <iostream> struct somestruct { uint64_t a = 7; }; inline ::std::ostream& operator <<(::std::ostream& s, const somestruct& q) { s << qa; return s; } int main(int argc, char **argv) { constexpr const auto inf = ::std::numeric_limits<somestruct>::infinity(); std::cout << inf << std::endl; return 0; } 

Godbolt to compile check

+5
source share
2 answers

The “why” questions are known to be incontrovertible, but the direct answer is: as he pointed out :

 namespace std { template<class T> class numeric_limits { // ... static constexpr T infinity() noexcept { return T(); } // ... }; } 

With additional text that is infinity() :

Value for all specializations for which has_infinity != false

In your case, numeric_limits<somestruct>::has_infinity is false , so infinity() does not make sense.

+14
source

According to C ++ 17 [numeric.limits] / 1 by default for the function in question:

 static constexpr T infinity() noexcept { return T(); } 

You did not define any specialization, so you get the default value.

link cppreference.com

+5
source

Source: https://habr.com/ru/post/1276111/


All Articles