0

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 nice for use with, say, unicode strings, where it gives you character count.

I'm hoping Qt has a generic version.

danielweberdlc
  • 452
  • 1
  • 8
  • 16

2 Answers2

1

_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
  • 222,467
  • 53
  • 283
  • 367
  • I just added a macro conditionally. the MS version apparently does something a bit more complete than this with templates, to ensure the argument is an array-type, but this works for what I need. – danielweberdlc May 23 '12 at 23:59
0

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.

Community
  • 1
  • 1
parsley72
  • 8,449
  • 8
  • 65
  • 98