问题描述
我需要将元组的值转发给成员初始值设定项:
I need to forward the values of a tuple to a member initializer:
struct Struct {
Member1 member1;
Member2 member2;
template<typename Tuple1, typename Tuple2>
Struct( Tuple1&& tuple1, Tuple2&& tuple2 )
: member1(tuple1...), member2(tuple2...)
{}
};
上面的代码显然是无效的.怎么表达?
The code above obviously isn't valid. How can I express it?
Member1
和 Member2
没有默认/复制/移动构造函数.
Member1
and Member2
have no default/copy/move constructor.
我了解 std::apply
,正如 如何将元组扩展为可变参数模板函数的参数?.我也知道 std::make_from_tuple
.但我不知道如何在成员初始值设定项中使用这些.
I know about std::apply
, as suggested in How do I expand a tuple into variadic template function's arguments?. I also know about std::make_from_tuple
. But I wouldn't know how to use any of these in a member initializer.
任何 C++ 标准都可以(最好是 C++17,但 C++20 也可以).
Any C++ standard is fine (preferably C++17, but C++20 would work as well).
澄清一下,我的真正目标是创建一个 Struct
,向它传递两组可变参数以完美转发它们以初始化 member1
和 member2代码>.我以为分组"将两组组合成元组可能是一个好主意,因为这就是
std::map::emplace
所做的.其他方法也可以(例如,在两组可变参数之间传递一个特殊对象).
To clarify, my real goal is to create a Struct
, passing it two sets of variadic arguments to perfect-forward them to initialize member1
and member2
. I thought that "grouping" the two sets into tuples could have been a good idea, since that's what std::map::emplace
does. Other approaches would work as well (e.g. passing a special object between the two sets of variadic arguments).
推荐答案
std::make_from_tuple
确实是正确的选择:
#include <tuple>
struct Member1 {
Member1(int x,float y, char z){}
Member1(const Member1& other)=delete;
Member1(Member1&& other)=delete;
};
struct Member2 {
Member2(int x,float y, char z){}
Member2(const Member2& other)=delete;
Member2(Member2&& other)=delete;
};
struct Struct {
Member1 member1;
Member2 member2;
template<typename Tuple1, typename Tuple2>
Struct(Tuple1&& tuple1, Tuple2&& tuple2)
: member1(std::make_from_tuple<Member1>(std::forward<Tuple1>(tuple1))),
member2(std::make_from_tuple<Member2>(std::forward<Tuple2>(tuple2)))
{}
};
int main(){
Struct c(std::tuple{1,1.1,'c'},std::tuple{2,2.2,'x'});
}
这篇关于如何将元组的值转发给成员初始值设定项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!