Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom brace initializer

Let's say I have this struct:

struct MyStruct {
    int field1;
    char *field2;
    MyStruct(int a, char* b): field2(b) {
        field1 = doStuff(a);
    }
    MyStruct(int a): MyStruct(a, nullptr) {}
    ~MyStruct();
}

As far as I know this is not an aggregate as I have some constructors.

What I want to achieve is to use the curly brace initializer in a custom way, which means using a code like this:

MyStruct x = { 1, "string" };

which implicitly calls the proper constructor (the first one in this case).

Is this possible in any way?

like image 928
Fylax Avatar asked Feb 13 '26 22:02

Fylax


1 Answers

You're almost there. MyStruct x = { 1, "string" }; is called copy list initialization. It will attempt to construct a MyStruct from the available constructors with the parameters supplied from the braced-init-list

Your issue is that your constructor takes a char* while "string" is a const char[N] which can decay to a const char*, not a char*. So making thing that change

struct MyStruct {
    int field1;
   const char* field2;
    MyStruct(int a, const char* b): field2(b) {
        field1 = a;
    }
    MyStruct(int a): MyStruct(a, nullptr) {}
    ~MyStruct() {}
};

Then

MyStruct x = { 1, "string" };

Will work. If you want to make this a little more bullet proof you can change field2 to be a std::string and use

struct MyStruct {
    int field1;
    std::string field2;
    MyStruct(int a, const std::string& b): field1(a), field2(b) {}
    MyStruct(int a): MyStruct(a, "") {}
    ~MyStruct() {}
};
like image 57
NathanOliver Avatar answered Feb 15 '26 10:02

NathanOliver