c++ - 可以将 std::numeric_limits<T> 专门用于用户定义的类数类吗?

标签 c++ types numbers standards

std::numeric_limits<T> 的文档说它不应该专门用于非基本类型。类似数字的用户定义类型呢?如果我定义自己的类型 T它表示一个数值并重载数字运算符,其信息由 numeric_limits 表示有道理——如果我专攻 numeric_limits 会有什么问题吗?适合那种类型?

最佳答案

简答:

去吧,不会有坏事发生的。

长答案:

C++ 标准广泛保护 ::std C++11 17.6.4.2.1 中的命名空间,但在第 1 段和第 2 段中特别允许您的情况:

The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.

[...] A program may explicitly instantiate a template defined in the standard library only if the declaration depends on the name of a user-defined type and the instantiation meets the standard library requirements for the original template.

较旧的 C++03 在 17.4.3.1/1 中有类似的定义:

It is undefined for a C++ program to add declarations or definitions to namespace std or namespaces within namespace std unless otherwise specified. A program may add template specializations for any standard library template to namespace std. Such a specialization (complete or partial) of a standard library template results in undefined behavior unless the declaration depends on a user-defined name of external linkage and unless the specialization meets the standard library requirements for the original template.

在通过这个基本的垫脚石之后,您已经指出,C++03 18.2.1/4 禁止专门化 ::std::numeric_limits对于某些类型:

Non-fundamental standard types, such as complex (26.2.2), shall not have specializations.

最新的 C++11 18.3.2.1/4 的措辞略有不同:

Non-arithmetic standard types, such as complex<T> (26.4.2), shall not have specializations.

然而,这两种公式都允许对非标准类型进行专门化,T是,因为您自己定义了它(正如@BoPersson 已经在评论中指出的那样)。

注意事项

C++11 18.3.2.3/1 提示您应该(但不要求您)确保您的特化拥有所有成员。

此外,您可能希望确保您的特化不违反 C++11 18.3.2.3/2:

The value of each member of a specialization of numeric_limits on a cv-qualified type cv T shall be equal to the value of the corresponding member of the specialization on the unqualified type T.

这实质上意味着,如果您希望将其专门用于 T ,您也应该为 T const 这样做, T volatileT const volatile .

关于c++ - 可以将 std::numeric_limits<T> 专门用于用户定义的类数类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16122912/

相关文章:

c++ - 在 C++ 中使用 min 和 max 函数

c# - 开源最小网络服务器?

c++ - MPI_Scatter,分散对角元素

mysql - 这里有文本到数字的转换吗?

c++ - 删除表达式

C++ wchart_t 警告 : character constant too long for its type

ios - 开启 UIButton title : Expression pattern of type 'String' cannot match values of type 'String?!'

regex - 提取包含一个或多个数字的文件名,然后将 cat 内容提取到输出文件

java - 如何将数字、空格和逗号组成的字符串更改为整数数组列表

javascript - 将零移动到数组的末尾并保留非零元素而不改变顺序