Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member initializer list: initialize two members from a function returning a tuple

Can multiple members be initialized in the member initializer list from a tuple obtained by a function?

With returning multiple values via tuples becoming more popular I hope there is a solution for this. I see no reason other than a language limitation why this would not be possible.


This is a mcve for what I have:

auto new_foo(std::size_t size) -> std::tuple<std::unique_ptr<char[]>, int*>
{
    auto buffer = std::make_unique<char[]>(size * sizeof(int) + 8);
    auto begin = static_cast<int*>(static_cast<void*>(buffer.get() + 4));
    return std::make_tuple(std::move(buffer), begin);
}

struct X {
    std::unique_ptr<char[]> buffer_{nullptr};
    int* begin_{nullptr};
    std::size_t size_{0};

    X(std::size_t size) : size_{size}
    {
        std::tie(buffer_, begin_) = new_foo(size);
    }
};

Can this be done?:

    X(std::size_t size)
        : buffer_{ ??? },
          begin_{ ??? },
          size_{size}
    {
    }

I simply cannot call new_foo once for each member initialization (as it returns another tuple with every call). So

    X(std::size_t size)
        : buffer_{std:get<0>(new_foo(size)},
          begin_{std:get<1>(new_foo(size)},
          size_{size}
    {
    }

it's not possible (even if it this wasn't the case, calling multiple times to get the same result is less than optimal)

Another solution I thought about was to hold the members as a tuple. I discarded that as I need the two members properly named inside the class and not accessed with get<0> and get<1>.

Yet another workaround would be to create a simple separate struct to hold the two members. This way they would have names, but add another level of qualifier, and possible I would have to create a copy ctor for it (because of the unique_ptr).


As reported here C++1z will have Structured bindings (D0144R0) which will make this possible:

auto {x,y,z} = f();

As I didn't find the full paper, I cannot tell if this will help in the context of member initializer list. I suspect not.

like image 370
bolov Avatar asked Feb 11 '16 23:02

bolov


1 Answers

Define another (possibly private) constructor that takes the tuple and delegate to it.

  private:
    X(std::tuple<std::unique_ptr<char>, int*> t, std::size_t size)
            : buffer_{std::move(std:get<0>(t))},
              begin_{std:get<1>(t)},
              size_{size}
    { }

 public:
    X(std::size_t size) : X{new_foo(size), size}
    { }
like image 136
Jonathan Wakely Avatar answered Sep 20 '22 10:09

Jonathan Wakely