My C++ program uses unsigned ints of different widths to express constraints on what data can be represented. For example, I have a file whose size is a uint64_t
, and I wish to read it in chunks with a buffer whose size is a size_t
. A chunk is the smaller of the buffer size and the (remaining) file size:
uint64_t file_size = ...;
size_t buffer_size = ...;
size_t chunk_size = std::min(buffer_size, file_size);
but this fails because std::min
requires that both parameters have the same type, so I must cast up and then back down:
size_t chunk_size = \
static_cast<size_t>(std::min(static_cast<uint64_t>)buffer_size, \
file_size));
This casting ought to be unnecessary, because it is obvious that min(size_t, uint64_t)
will always fit in a size_t
.
How can I write a generic min
function that takes two (possibly different) unsigned types, and whose return type is the smaller of the two types?