用于确定各种变量的大小(以字节为单位)的模板
Template to determine the size in bytes of various variables
我需要一种通用的方法来确定当前分配的连续变量的内存大小,而无需为每种类型创建大量模板。我主要需要这个用于 C++ 样式容器的模板函数,但是(因为我事先不知道类型)我需要它也与原始 C 类型兼容。
编辑了问题,使其听起来更具描述性和迂腐性。
C++14 中的解决方案,假设我理解你的意思:
template <class Container>
constexpr auto byte_size(const Container& container) {
using std::begin;
using std::end;
return (end(container) - begin(container)) * sizeof(container[0]);
}
请注意,即使容器为空,这也会起作用,因为 sizeof
不会计算其操作数。
虽然它不适用于 std::vector<bool>
——我猜你必须为此添加专业化。
我需要一种通用的方法来确定当前分配的连续变量的内存大小,而无需为每种类型创建大量模板。我主要需要这个用于 C++ 样式容器的模板函数,但是(因为我事先不知道类型)我需要它也与原始 C 类型兼容。
编辑了问题,使其听起来更具描述性和迂腐性。
C++14 中的解决方案,假设我理解你的意思:
template <class Container>
constexpr auto byte_size(const Container& container) {
using std::begin;
using std::end;
return (end(container) - begin(container)) * sizeof(container[0]);
}
请注意,即使容器为空,这也会起作用,因为 sizeof
不会计算其操作数。
虽然它不适用于 std::vector<bool>
——我猜你必须为此添加专业化。