The answer to this question says that C doesn't provide any means to detect the size of parameter passed through ellipsis:
How to detect the size of the parameters that are passed through ellipsis?
Is there C++ solution to this problem?
For C style vararg functions, no. For C++ style vararg templates, yes. You use sizeof ... operator for that. See cppreference:
#include <iostream>
template <typename ...Args>
void print_arg_cnt(Args... args)
{
std::cout << "Arg count: " << sizeof ...(Args) << '\n';
}
int main()
{
print_arg_cnt(1, 1.1, 'a');
}
Arg count: 3
Godbolt
If you want to find out the total number of bytes those arguments occupy, you can do this:
template <typename ...Args>
void print_args_size(Args... args)
{
auto constexpr size = (sizeof(Args) + ... + 0); // +0 for the empty case
std::cout << "Total size: " << size << '\n';
}
Or sizes can be printed individually as in cigien's answer.
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