[英]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). 我无法为每个成员初始化调用
new_foo
(因为它会在每次调用时返回另一个元组)。 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>
. 我放弃了,因为我需要在类中正确命名的两个成员,而不是使用
get<0>
访问并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
). 这样他们就会有名字,但是添加另一个限定符级别,并且我可能需要为它创建一个副本ctor(因为
unique_ptr
)。
As reported here C++1z
will have Structured bindings (D0144R0) which will make this possible: 正如本文所述,
C++1z
将具有结构化绑定 (D0144R0),这将使这成为可能:
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}
{ }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.