简体   繁体   中英

Excess elements in struct initializer when nested std::array

I'm getting Excess elements in struct initializer on the return line of the following:

using triangleColor = std::array<std::array<float, 4>, 3>;

triangleColor colorBlend(TriangleColorBlend c){
    switch (c) {
        case TriangleColorBlend::white:
            return {{1.0,1.0,1.0,1.0},{0.7,0.7,0.7,1.0},{0.5,0.5,0.5,1.0}};
            break;

        ... // other cases
    }
}

I was hoping the curly-brace literal would work in the nested fashion, as it works fine if I do this with just a single std::array, not nested.

Is the above simply not possible, and why not?

Note, the suggested duplicate doesn't really address the odd behavior of std::array in a nested situation.

triangleColor colorBlend(TriangleColorBlend c) {
    switch (c) {
    case TriangleColorBlend::white:
        return {{
            {{ 1.0f, 1.0f, 1.0f, 1.0f }},
            {{ 0.7f, 0.7f, 0.7f, 1.0f }},
            {{ 0.5f, 0.5f, 0.5f, 1.0f }}
        }};
    default:
        throw std::invalid_argument("c");
    }
}

Online Demo

There were two issues with your code:

  1. You were lacking braces for the inner arrays.
  2. As noted by @Praetorian, colorBlend had no return value for the default case.

You are missing a set of brackets.

return {{1.0,1.0,1.0,1.0},{0.7,0.7,0.7,1.0},{0.5,0.5,0.5,1.0}};

Should be

return {{{1.0,1.0,1.0,1.0},{0.7,0.7,0.7,1.0},{0.5,0.5,0.5,1.0}}};

You can see it working in this minimal example

Another work around:

triangleColor colorBlend(TriangleColorBlend c){
   using t1 = std::array<float, 4>;
   switch (c) {
      case TriangleColorBlend::white:
         return {t1{1.0,1.0,1.0,1.0},t1{0.7,0.7,0.7,1.0},t1{0.5,0.5,0.5,1.0}};
         break;

      default:
         break;
   }
   return triangleColor{};
}

The answer to the question of why

        return {{1.0,1.0,1.0,1.0},{0.7,0.7,0.7,1.0},{0.5,0.5,0.5,1.0}};

does not work can be found at https://stackoverflow.com/a/8192275/434551 :

std::array is an aggregate by the rules of C++11, and therefore it can be created by aggregate initialization. To aggregate initialize the array inside the struct, you need a second set of curly braces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM