成员初始化器列表:从返回元组的函数初始化两个成员 [英] 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.
这是我所拥有的mcve :
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);
}
};
可以这样做吗?:
X(std::size_t size)
: buffer_{ ??? },
begin_{ ??? },
size_{size}
{
}
I不能为每个成员初始化一次调用 new_foo
(因为每次调用都会返回另一个元组)。因此
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)
我想到的另一种解决方案是将成员保持为元组,因为我需要在类中正确命名两个成员并且不能使用 get< ; 0>
和 get< 1>
。
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>
.
另一种解决方法是创建一个简单的单独的结构来容纳这两个成员。这样,它们将具有名称,但是又增加了一个限定符级别,可能我必须为其创建一个副本ctor(因为 unique_ptr
)。
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
).
如此处 C ++ 1z
将具有结构化绑定(D0144R0),这将使其成为可能:
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.
推荐答案
定义另一个(可能是私有的)构造函数,该构造函数接受元组并委托给它。
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}
{ }
这篇关于成员初始化器列表:从返回元组的函数初始化两个成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!