does Qt implement _countof or equivalent?
I really like using the _countof() macro in VS and I'm wondering if there is an OS-generic implementation of this in Qt.
For those unaware, _countof() gives you the number of elements in the array. so,
wchar_t buf[256];
_countof(buf) => 256 (characters) sizeof(buf) => 512 (bytes)
It's very ni开发者_如何学Pythonce for use with, say, unicode strings, where it gives you character count.
I'm hoping Qt has a generic version.
_countof
is probably defined like this:
#define _countof(arr) (sizeof(arr) / sizeof((arr)[0]))
You can use a definition like this with any compiler and OS.
If there is no such macro provided by Qt you can simply define a custom one yourself in one of your header files.
sth's code will work fine, but won't detect when you're trying to get the size of a pointer rather than an array. The MS solution does this (as danielweberdlc says), but it's possible to have this as a standard solution for C++:
#if defined(Q_OS_WIN)
#define ARRAYLENGTH(x) _countof(x)
#else // !Q_OS_WIN
template< typename T, std::size_t N >
inline std::size_t ARRAYLENGTH(T(&)[N]) { return N; }
#endif // !Q_OS_WIN
A more detailed description of this solution is given here.
精彩评论