Last active
December 14, 2015 17:58
-
-
Save mooware/5125494 to your computer and use it in GitHub Desktop.
Type-safe way to get the length of an array in C++.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In C/C++, the idiom (sizeof(arr) / sizeof(*arr)) is often used to get the length of an array. | |
// But this will return incorrect results if arr is not actually an array, but a pointer. | |
// The following function template provides a type-safe way to get the length of an array, | |
// by "destructuring" the type and reading the array length from there. | |
#include <cstddef> // for size_t | |
template <typename T, size_t N> | |
constexpr size_t sizeof_array(T (&)[N]) | |
{ | |
return N; | |
} | |
// here is a fallback for compilers without support for constexpr: | |
// this function takes a reference to array of type T[N], and returns a reference to char. | |
// the return type is then used with sizeof() to get N (compare with MSVC's _countof). | |
template <typename T, unsigned int N> char (&_return_sizeof_array(T (&)[N]))[N]; | |
#define sizeof_array(__arr__) sizeof(_return_sizeof_array((__arr__))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment