- added safety check to the countof macro

Tue, 08 Apr 2014 11:00:29 +0300

author
Santeri Piippo <crimsondusk64@gmail.com>
date
Tue, 08 Apr 2014 11:00:29 +0300
changeset 709
47a2f9d10ebe
parent 708
3155f2c05f89
child 710
86a19bfc34de

- added safety check to the countof macro

src/macros.h file | annotate | diff | comparison | revisions
--- a/src/macros.h	Tue Apr 08 10:54:32 2014 +0300
+++ b/src/macros.h	Tue Apr 08 11:00:29 2014 +0300
@@ -17,12 +17,25 @@
  */
 
 #pragma once
+#include <type_traits>
 
 #ifndef __GNUC__
 # define __attribute__(X)
 #endif
 
-#define countof(A) ((int) (sizeof A / sizeof *A))
+// =============================================================================
+//
+#define countof(A) (safeCountOf<std::is_array<decltype(A)>::value, (sizeof A / sizeof *A)>())
+
+template<bool isArray, size_t elems>
+inline constexpr int safeCountOf() __attribute__ ((always_inline));
+
+template<bool isArray, size_t elems>
+inline constexpr int safeCountOf()
+{
+	static_assert (isArray, "parameter to countof must be an array");
+	return elems;
+}
 
 // =============================================================================
 //

mercurial