Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I accidentally fed a default initializeable struct to std::numeric_limits<somestruct>::infinity(). What I got back was a default struct.

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 << q.a;
    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 for compilation verification

like image 331
Bomaz Avatar asked Mar 27 '18 12:03

Bomaz


1 Answers

"Why" questions are notoriously unanswerable, but the direct answer is: that's how it's specified:

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

With the extra text that infinity() is:

Meaningful for all specializations for which has_­infinity != false

In your case, numeric_limits<somestruct>::has_infinity is false, so infinity() isn't meaningful.

like image 152
Barry Avatar answered Sep 28 '22 10:09

Barry