c++ - What is happening with this code? -
i'm trying develop android keyboard using android aosp keyboard source model. there's quite bit of jni code, c++ bit rusty, , i'm having trouble following definition macro nelems
:
// disclaimer: see compile error if use macro against variable-length array. // sorry inconvenience. isn't supported. template <typename t, int n> char (&arraysizehelper(t (&array)[n]))[n]; #define nelems(x) (sizeof(arraysizehelper(x)))
when try compile, second line of code (just above #define
) lights error:
declaration of reference variable requires initializer
the error message makes sense me; aosp code not. symbol arraysizehelper
occurs else in aosp code or make files (that is, far can tell it's not macro else).
from name of macro, guess supposed evaluate number of elements in array. far know, though, usual way be:
#define nelems(x) (sizeof(x) / sizeof((x)[0]))
so i'm wondering if else going on here.
i'd appreciate explanation of code supposed , guidance on compile error.
edit: i'm compiling through android studio 1.3 rc 3, android ndk r10e, , gradle 2.5. compilation uses various toolchains (as described in this android documentation). strangely, above code compiles , executes correctly (perhaps did). however, android studio still displays error on line. displays error on every use of nelems
:
error after macro substitution: many arguments, expected 0
i'm thinking ide code analysis error, not compiler or coding problem. original question code itself, i'm marking thread answered. i'll open question seems ide problem. explanations!
this:
template <typename t, int n> char (&arraysizehelper(t (&array)[n]))[n];
declares function named arraysizehelper
takes reference array of n
t
s named array
, returns reference array of char[n]
. there no definition given.
sizeof()
not require definition of function - it's operand unevaluated. operates on type: sizeof(arrayhelper(x))
evalutes sizeof(char[n])
if type of x
t[n]
(and doesn't compile otherwise).
it's horribly complex way of writing:
template <typename t, size_t n> constexpr size_t array_size(t (&)[n]) { return n; }
which far far easier understand. , doesn't require macro.
Comments
Post a Comment