areuz areuz - 1 year ago 65
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download