Search code examples
c++integral

How to call an integral types base on actual type in a cpp template?


How can I call an integral types base on actual type in a cpp template? For example, when the actual type is int, call INT_MAX. And when the actual type is unsigned long, call ULONG_MAX;

Of course I can just write a if-else statement, but is there any other way to do that? Or what's the best way to write this part of code?


Solution

  • The best standard way is to rely on the <limits> header. A template already exists that does what you want. It's std::numeric_limits with its static max function. So what you want will look like this:

    auto max_int = std::numeric_limits<int>::max();