Search code examples
c++c++11compiler-errorsclangstdarray

Compiler error initializing std::array of structs with clang


I have some code:

std::array<JNINativeMethod, 26> methods = {
    { "nativeCreate", "(Ljava/lang/String;)J", reinterpret_cast<void*>(&nativeCreate) },
    { "nativeDestroy", "(J)V", reinterpret_cast<void*>(&nativeDestroy) },
    ...
    { "nativeToggleDebug", "(J)V", reinterpret_cast<void*>(&nativeToggleDebug) }}
};

That I am trying to compile with the Android NDKs clang 3.4 compiler.

However that code gives me this error:

jni/JNI.cpp:252:9: error: excess elements in struct initializer
        { "nativeDestroy", "(J)V", reinterpret_cast<void*>(&nativeDestroy) },
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Unless I add another set of braces:

std::array<JNINativeMethod, 26> methods = {{
    { "nativeCreate", "(Ljava/lang/String;)J", reinterpret_cast<void*>(&nativeCreate) },
    { "nativeDestroy", "(J)V", reinterpret_cast<void*>(&nativeDestroy) },
    ...
    { "nativeToggleDebug", "(J)V", reinterpret_cast<void*>(&nativeToggleDebug) }}
}};

This seems strange to me but after finding this discussion about Visual C++: http://social.msdn.microsoft.com/forums/vstudio/en-US/e5ad8fa5-c9e8-4328-a7fa-af7a47ce2492/initialising-a-stdarray-of-structs

I want to know if this is incorrect C++11 syntax, or just a defect in clang 3.4.

Is it related to the bug mentioned in Initializing simple structs using initializer lists with clang


Solution

  • std::array is an aggregate class containing an array; so you need two pairs of braces, one around the class member initialiser(s), and one around the array element initialiser(s).

    I believe C++14 will relax this requirement, allowing the nested array elements to be initialised from the outer initialser list.