31

In the C++ Standard Library the value std::numeric_limits<T>::max() is specified as a function. Further properties of a specific type are given as constants (likestd::numeric_limits<T>::is_signed). All constants that are of type T are given as functions, whereas all other constants are given as, well, constant values.

What's the rationale behind that?

q-l-p
  • 4,304
  • 3
  • 16
  • 36
ablaeul
  • 2,750
  • 20
  • 22
  • 3
    http://www.archivum.info/comp.lang.c++/2010-01/01066/numeric_limits-lt-gt-::max%28%29.html –  May 04 '10 at 14:48
  • max is not constant and may vary with compiler flags. – Martin York May 04 '10 at 14:57
  • 3
    @Martin: I don't see how that matters. Surely, the compiler flags could just control how the constant is initialized. – jalf May 04 '10 at 15:03
  • @jalf: As an implementation detail you are correct and it makes no difference functions verses variables. But by using functions you are implying that this information is not constant and is computed (even if it is a const expression inside). I like the distinction as information is power. – Martin York May 04 '10 at 15:20
  • See also: http://stackoverflow.com/questions/2738435/using-numeric-limitsmax-in-constant-expressions – Rob Kennedy May 04 '10 at 16:18

1 Answers1

20

To expand on Neil's remark, std::numeric_limit<T> is available for any number type including floating point numbers, and if you dig through the comp.lang.c++ thread, you'll see the mention that it might not be possible to define the static variables for floating point values.

So, for consistency they decided to put both integral and floating points behind methods.

It will change with C++0x, so there's hope.

spinkus
  • 7,694
  • 4
  • 38
  • 62
Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
  • Now I'm really curious to know why it might not be possible to define a floating point static variable. Could you elaborate? – MicroVirus Oct 04 '16 at 13:24
  • 1
    @MicroVirus: Oh my... I can't guarantee that this is what I was thinking about 6 years ago (and counting)... but I would bet on [Floating Point Rounding Modes](http://en.cppreference.com/w/cpp/numeric/fenv/FE_round). A compiler must interpret a floating point literal `0.0123456789` as an actual `float` or `double` value if you want it to be stored in ROM... but how should it round the result? It cannot predict which rounding mode will be used at run-time! C++11 defined what rounding modes affect and what they do NOT affect, making it possible to have portable static initialization of floats. – Matthieu M. Oct 04 '16 at 13:33