'C++ create tree structure with initializer_list

I'm trying to build a tree-like structure in C++ and I found out about initializer_list and tried to implement it as part of my code. I want the code to be able to create an object from a set of properties, be able to apply some methods and then append at the end an array of children.

So I came up (after a lot of tries and failure) with this:

#include <vector>
#include <initializer_list>

struct Branch
{
    // Branch properties
    int val;
    std::vector<Branch> data;

    Branch(int i): val(i) {}

    Branch& operator=(std::initializer_list<Branch> list)
    {
        data = list;
        return *this;
    }

    // Some function with specific behaviour
    Branch& bar() {
        return *this;
    }
};

int main()
{
    auto Main = Branch(1).bar() = {
        Branch(2) = {
            Branch(4)
        },
        Branch(3).bar(),
    };
    return Main.val;
}

As you can see, in my code I first pass the int property and then (sometimes) call a function depending on whether I want some specific traits for that branch or not. Then I attach a list for its children.

Now, I know that there are probably many things wrong with my code. For once I wanted to pass "Branch&" as type to the initializer_list (and vector) so it does not create a copy but then the compiler said no operator "=" matches these operands inside the main function.

So, here is my question. Is there a way to solve this? Maybe a workaround to pass a reference... Or maybe another implementation with similar effects.

I also tried with std::array instead of vector but it seems like they are not compatible.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source