areuz areuz - 1 month ago 5x
C++ Question

Template to determine the size in bytes of various variables

I need a universal way of determining the memory size of a currently allocated contiguous variable without the need to create tons of templates for each one of the types. I mostly need this template function for C++ style containers, but (because I don't know the Type in advance) I need it to be also compatible with primitive C types.

Edited the question to sound a little bit more descriptive and pedantic.


Solution in C++14, assuming I understood what you meant:

template <class Container>
constexpr auto byte_size(const Container& container) {
    using std::begin;
    using std::end;
    return (end(container) - begin(container)) * sizeof(container[0]);

Note that this will work even if the container is empty, since sizeof does not evaluate its operand.

It won't work for std::vector<bool> though---guess you'll have to add a specialization for that.