Created
February 2, 2015 12:22
-
-
Save gpakosz/23dcbb773793aa4aafde to your computer and use it in GitHub Desktop.
C++ array_length, reply to http://www.g-truc.net/post-0708.html
This file contains hidden or 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
#include <cstddef> | |
#include <iostream> | |
#define array_length(a) sizeof(implementation::array_length_requires_array_argument(a)) | |
namespace implementation { | |
template<typename T, size_t N> | |
char (&array_length_requires_array_argument(T (&)[N]))[N]; | |
} // namespace implementation | |
// void foo(const int a[]) | |
// { | |
// for (int i = 0; i < array_length(a); ++i) // error | |
// a[i] = 0; | |
// } | |
int main() | |
{ | |
int a[2]; | |
int b[2][3]; | |
std::cout << array_length(a) << std::endl; | |
std::cout << array_length(b) << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment