patraulea
patraulea

Reputation: 916

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)

Upvotes: 2

Views: 112

Answers (2)

Marek R
Marek R

Reputation: 38112

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)

Upvotes: 9

teapot418
teapot418

Reputation: 2578

Try explicitly specifying the template parameter:

std::max<size_t>(s.size(), 10);

compiles fine, it's clear enough and not too ugly.

Upvotes: 9

Related Questions