jeudi 6 avril 2017

Nice way to truncate an integer

I have a function which is given a buffer which accepts to be filled up to a size_t length; however, the actual call which fills it wants an int as max length.

So, in case the parameter cannot fit in an integer, I want it truncated to the maximum value that can fit; as I couldn't get more data anyway.

I can do this

int truncatedMaxLen = static_cast<int>(std::min<std::size_t>(maxLength, (std::numeric_limits<int>::max)()));

Any less ugly ways?

Aucun commentaire:

Enregistrer un commentaire