我正在用 C++ 开发一个库,以帮助开发人员完成某些任务。 通常,为了以动态方式(不使用#define SIZE 或 static int SIZE)计算整数数组(例如)的大小,我会执行 sizeof(v)/sizeof(int)。我正在尝试编写一段可以自动为我做这些事情的代码,我决定调用 if lengthof。 代码在这里:
template <class T> int _typesize(T*) { return sizeof(T); }
#define lengthof(x) (sizeof(x) / _typesize(&x))
我使用模板获取数组的类型,然后以字节为单位返回它的大小。在 GCC 中,我知道可以使用 typeof,因此我可以将 _typesize(&x) 替换为 sizeof(typeof(x)),但在 MSVC 上这是不可能的。 _typesize 是一种兼容的方式,但我认为它可能很昂贵,因为它将指针作为拷贝传递。有一种优雅的方法可以做到这一点吗?
最佳答案
此任务不需要宏。如果你有一个符合标准的编译器
template<class T, size_t len>
constexpr size_t lengthof(T(&)[len]) {return len;}
//the parameter is an unnamed reference to a `T[len]`,
//where `T` is deduced as the element type of the array
//and len is deduced as the length of the array.
//similar to `T(*)[len]` in C, except you can pass the array
//directly, instead of passing a pointer to it.
//added benefit that if you pass a `T*` to it, it produces a compiler error.
或者,如果您使用的 Visual Studio 尚未符合标准...
template<class T, size_t len>
std::integral_constant<size_t, len> lengthof(T(&)[len]) {return {};}
//VC++ doesn't have constexpr, so we have to use `std::integral_constant` instead :(
//but how it works is 100% identical
如果你想要一种更便携的方式,宏仍然是最好的方法:
#define lengthof(arr) sizeof(arr) / sizeof(arr[0])
//doesn't respect namespaces, evaluates arguments multiple times
//and if you pass a `T*` to it, it evaluates to `1` depending on context.
但重申一下我的意见,我会考虑所有这些糟糕的代码。使用 std::vector
或 std::array
。
关于c++ - 计算固定数组中元素的数量(类似于 sizeof),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22641758/