First of all, there is no "easy" way of computing the storage of everything from the STL.
Following your try, the best I could think of is writing your own sizeof
function which you will implement for everything you like, e.g.:
template<typename T>
size_t metaSizeOf(const T& t)
{
return sizeof(T);
}
and then specialize it at will, e.g for a vector you would need something like:
template<typename T, typename Alloc, template <typename, typename> class V>
size_t metaSizeOf(const V<T, Alloc>& v)
{
size_t bytes = sizeof(V<T, Alloc>);
for(const auto& t: v) bytes += metaSizeOf(t);
return bytes;
}
And copy/paste the same code with all template interfaces you have, e.g. for sets:
template<typename T, typename Compare, typename Alloc, template <typename, typename, typename> class V>
size_t metaSizeOf(const V<T, Compare, Alloc>& v)
{
size_t bytes = sizeof(V<T, Compare, Alloc>);
for(const auto& t: v) bytes += metaSizeOf(t);
return bytes;
}
And so on. You can also write your own implementation for specific cases. For example for arrays you can write a generic function:
template<typename T, std::size_t N, template <typename, std::size_t> class V>
size_t metaSizeOf(const V<T, N>& v)
{
size_t bytes = sizeof(V<T, N>);
for(const auto& t: v) bytes += metaSizeOf(t);
return bytes;
}
But you can also opt for a dedicated, optimized version for arrays only:
template<typename T, std::size_t N>
size_t metaSizeOf(const std::array<T, N>&)
{
return sizeof(std::array<T, N>) + N * sizeof(T);
}
Example @ IdeOne.com
But as others pointed out, you will only count the size of the raw data, which is far from accurate. The memory usage of STL containers can be surprising.