I am trying to figure out which is the most idiomatic way implement a function over a variadic type list. For example, computing the maximum size of all the types. I understand there exist several approaches to accomplish such a task, but I would like to know when to choose which strategy.
These are the mechanisms I would consider (there may exist more, please mention if so):
Type traits (ideally succinctly with using declarations):
template <typename Head>
using max_size = typename std::integral_constant<size_t, sizeof(Head)>::type;
template <typename Head, typename... Tail>
using max_size = ?;
constexpr functions:
template <typename Head>
constexpr size_t max_size() { return sizeof(Head); }
template <typename Head, typename... Tail>
constexpr size_t max_size() { ? }
My question is twofold:
What features of the computation determine what strategy to choose?
In each case, how would an example implementation for the maximum size example described above look like?
I personally prefer functions rather than traits, I find them easier to manipulate and more natural. But that's certainly subjective ;)
#include <iostream>
template <typename Head>
constexpr size_t max_size() { return sizeof(Head); }
template <typename Head, typename Next, typename... Tail>
constexpr size_t max_size() {
return max_size<Head>() > max_size<Next, Tail...>() ?
max_size<Head>() : max_size<Next, Tail...>();
}
int main() {
std::cout << "int: " << max_size<int>() << "\n";
std::cout << "char, short, int: " << max_size<char, short, int>() << "\n";
std::cout << "char, double, int: " << max_size<char, double, int>() << "\n";
}
In action at liveworkspace:
int: 4
char, short, int: 4
char, double, int: 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With