如何使用 min/max 可能值(数字限制)初始化通用变量?

How do I initialize a generic variable with its min/max possible value (numeric limits)?

如何使用基础泛型类型的 min/max 可能值初始化泛型函数中的变量?我正在寻找 Nim 等同于 C++ 的 std::numeric_limits.

Nim 不需要特殊的模块。一般模式是使用 low(T)high(T) 来获取类型 T 的 min/max 可能值。默认情况下,这些函数为所有整数类型重载。通过为它们实现 lowhigh ,它可以很容易地扩展到浮点类型或任何其他类型。例如,以下代码适用于任何标准数字类型:

import typetraits # only required for priting the type name

proc high(T: typedesc[SomeReal]): T = Inf
proc low(T: typedesc[SomeReal]): T = NegInf

proc requiresNumericLimits[T]() =
  let minPossible = low(T)
  let maxPossible = high(T)
  echo "Min of type ", name(T), ": ", minPossible
  echo "Max of type ", name(T), ": ", maxPossible

requiresNumericLimits[int]()
requiresNumericLimits[int16]()
requiresNumericLimits[uint16]()
requiresNumericLimits[float32]()
requiresNumericLimits[float64]()

输出:

Min of type int: -9223372036854775808
Max of type int: 9223372036854775807
Min of type int16: -32768
Max of type int16: 32767
Min of type uint16: 0
Max of type uint16: 65535
Min of type float32: -inf
Max of type float32: inf
Min of type float64: -inf
Max of type float64: inf