为什么std :: numeric_limits <SomeStruct> :: infinity()"工作"?

Bom*_*maz 6 c++ templates std language-lawyer c++17

我不小心喂默认initializeable structstd::numeric_limits<somestruct>::infinity().我得到的是一个默认结构.

为什么标准允许这个编译并返回这样一个意外的值?

#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;
}
Run Code Online (Sandbox Code Playgroud)

Godbolt用于编译验证

Bar*_*rry 15

"为什么"这些问题众所周知是无法回答的,但直接的答案是:它是如何指定的:

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

有了多余的文字infinity()是:

对所有专业都有意义 has_­infinity != false

在你的情况下,numeric_limits<somestruct>::has_infinityfalse,所以infinity()没有意义.


M.M*_*M.M 5

根据C++ 17 [numeric.limits]/1,该函数的默认值为:

static constexpr T infinity() noexcept { return T(); }
Run Code Online (Sandbox Code Playgroud)

您尚未定义任何特化,因此您将获得默认值.

cppreference.com链接