In C++11 I can get agregated size of arguments in such way:
template<typename First, typename... Rest>
size_t getSize( const First& first, const Rest& ...rest )
{
return getSize(first) + getSize( rest... );
}
template <typename T>
size_t getSize( const T& )
{
return sizeof(T);
}
std::cout << "Size of arguments is: " << getSize( short(0), double(0.0) ) << std::endl;
Output will be: "Size of arguments is: 10". Is there any analogy for old C++?
P.S. Better solution for C++11 is also welcome
For C++11 I would use this which is evaluated by compile time.
#include <iostream>
template<typename First, typename... Rest>
struct total_size_of
{
static constexpr size_t value = total_size_of<First>::value + total_size_of<Rest...>::value;
};
template <typename T>
struct total_size_of<T>
{
static constexpr size_t value = sizeof(T);
};
int main() {
std::cout << "Size of arguments is: " << total_size_of<short, double>::value << std::endl;
return 0;
}
For Pre-C++11 I would use something like this (due to the lack of variadic templates).
#include <iostream>
template <typename T>
struct custom_size_of
{
static const size_t value = sizeof(T);
};
template <>
struct custom_size_of<void>
{
static const size_t value = 0;
};
template <typename One, typename Two = void, typename Three = void, typename Four = void>
struct total_size_of
{
static const size_t value = custom_size_of<One>::value + custom_size_of<Two>::value + custom_size_of<Three>::value + custom_size_of<Four>::value;
};
int main()
{
std::cout << "Size of arguments is: " << total_size_of<short, double>::value << std::endl;
return 0;
}
While the C++11 version is still easily adjusted into a function that automatically determines the the parameter types, there is no nice solution of doing this with pre-C++.
C++11:
template <typename...Args>
size_t get_size_of(Args...args)
{
return total_size_of<Args...>::value;
}
Pre-C++11:
template <typename One>
static size_t get_size_of(const One&)
{
return total_size_of<One>::value;
}
template <typename One, typename Two>
static size_t get_size_of(const One&, const Two&)
{
return total_size_of<One, Two>::value;
}
template <typename One, typename Two, typename Three>
static size_t get_size_of(const One&, const Two&, const Three&)
{
return total_size_of<One, Two, Three>::value;
}
template <typename One, typename Two, typename Three, typename Four>
static size_t get_size_of(const One&, const Two&, const Three&, const Four&)
{
return total_size_of<One, Two, Three, Four>::value;
}
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