use*_*937 0 c++ arrays typeof sizeof
我正在用C++开发一个库,以便为开发人员提供一些帮助.通常,为了以动态方式计算整数数组(例如)的大小(不使用#define SIZE或static int SIZE),我执行sizeof(v)/ sizeof(int).我正在尝试编写一段代码,可以自动为我做这些事情,我决定调用lengthof.代码在这里:
template <class T> int _typesize(T*) { return sizeof(T); }
#define lengthof(x) (sizeof(x) / _typesize(&x))
Run Code Online (Sandbox Code Playgroud)
我使用模板来获取数组的类型,然后以字节为单位返回其大小.在GCC中我知道可以使用typeof,所以我可以用sizeof(typeof(x))替换_typesize(&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.
Run Code Online (Sandbox Code Playgroud)
或者,如果您使用的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
Run Code Online (Sandbox Code Playgroud)
如果你想要一种更便携的方式,宏仍然是最好的:
#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.
Run Code Online (Sandbox Code Playgroud)
但重申我的评论,我会考虑所有这些糟糕的代码.使用std::vector或std::array.