Search code examples
c++templatesoverloadingstd

How to call std::max() with a size_t expression and a size_t literal constant?


Is there a std::max() overload or a simple way to clamp a size_t expression to a size_t constant, without doing static_cast<size_t>(10) ? The call below does not compile because 10 is not a size_t:

std::string s;
std::max(s.size(), 10)

Solution

  • Since C++23 there is spatial suffix to enforce size_t type for a literal:

    std::max(s.size(), 10UZ);
    

    Integer literal - cppreference.com

    The type of the literal

    The type of the integer literal is the first type in which the value can fit, from the list of types which depends on which numeric base and which integer-suffix was used:

    Suffix Decimal bases Binary, octal, or hexadecimal bases
    both z/Z and u/U - std::size_t (since C++23) - std::size_t (since C++23)

    https://godbolt.org/z/Y9Y79Tx8e

    As you can see feature is not fully supported yet (MSVC must be at least 19.43 - not available on compiler explorer yet)