Search code examples
c++c++11initializer-list

invalid use of brace-enclosed initializer list


I want to initialize the Foo class

class Foo {
public:
    struct MyStruct {
        uint8 i;
        char c;
    };

    Foo(MyStruct args...){

    };
};

But I'm getting a error

error: invalid use of brace-enclosed initializer list

auto test = Foo(
    {1, 'a'},
    {2, 'b'}
);

If I do this with variables, there is no error

Foo::MyStruct a1 = {1, 'a'};
Foo::MyStruct b2 = {2, 'b'};

auto test = Foo(a1, b2);

But I'm not comfortable with that, I'd like to make the code a compact


Solution

  • You need to explicitly state the types you're passing onto the constructor. The following compiles:

    auto test = Foo(
      Foo::MyStruct{1, 'a'},
      Foo::MyStruct{2, 'b'}
    );
    

    Note aschepler's comment though that Foo(MyStruct args...) is not a C++-style variadic function. So you might be in trouble if you're actually going to try and do something with the constructor arguments. In other words: you will get in trouble :).