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

本小妞迷上赌 提交于 2020-02-29 18:12:09

问题


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.


回答1:


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}
    { }


来源:https://stackoverflow.com/questions/35352020/member-initializer-list-initialize-two-members-from-a-function-returning-a-tupl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!