C++ 将元组和整数实例合并到引用的元组中
我在尝试从元组和整数值的混合构造引用元组时遇到了奇怪的行为 鉴于以下情况:C++ 将元组和整数实例合并到引用的元组中,c++,templates,tuples,c++14,template-meta-programming,C++,Templates,Tuples,C++14,Template Meta Programming,我在尝试从元组和整数值的混合构造引用元组时遇到了奇怪的行为 鉴于以下情况: struct A { int v = 1; }; struct B { int v = 2; }; struct C { int v = 3; }; A a; std::tuple<B,C> tpl; 然后 auto ref_tpl = std::tuple_cat(std::tie(a), as_ref(tpl)); 这可以很好地构建(在两个版本中) 不幸的是,只有引用元组(ref\u tpl)中源自整
struct A { int v = 1; };
struct B { int v = 2; };
struct C { int v = 3; };
A a;
std::tuple<B,C> tpl;
然后
auto ref_tpl = std::tuple_cat(std::tie(a), as_ref(tpl));
这可以很好地构建(在两个版本中)
不幸的是,只有引用元组(ref\u tpl
)中源自整数值的部分才能被成功赋值或读取
我使用的是C++14
和gcc9.3.0
欢迎提出任何想法,或洞察为什么这不起作用
最小工作示例:
#include <iostream>
#include <tuple>
#include <type_traits>
#include <utility>
#include <functional>
struct A { int v = 1; };
struct B { int v = 2; };
struct C { int v = 3; };
A a;
std::tuple<B,C> tpl;
template <class Tuple, size_t... Is>
constexpr auto as_ref_impl(Tuple t, std::index_sequence<Is...>) {
//return std::tuple_cat(std::tie(std::get<Is>(t))...);
return std::make_tuple(std::ref(std::get<Is>(t))...);
}
template <class...Args>
constexpr auto as_ref(std::tuple<Args...>& t) {
return as_ref_impl(t, std::index_sequence_for<Args...>{});
}
int main() {
using std::cout;
auto ref_tpl = std::tuple_cat(std::tie(a), as_ref(tpl));
// prints 1 2 3, as expected.
cout << a.v << std::get<0>(tpl).v << std::get<1>(tpl).v << std::endl;
std::get<0>(ref_tpl).v = 8; // works
std::get<1>(ref_tpl).v = 9; // does not work
std::get<2>(ref_tpl).v = 10; // does not work
// should output 8 9 10 instead outputs 8 2 3
cout << a.v << std::get<0>(tpl).v << std::get<1>(tpl).v << std::endl;
// should output 8 9 10, instead outputs garbage.
cout << std::get<0>(ref_tpl).v << std::get<1>(ref_tpl).v << std::get<2>(ref_tpl).v << std::endl;
return 0;
}
#包括
#包括
#包括
#包括
#包括
结构A{intv=1;};
结构B{intv=2;};
结构C{intv=3;};
A A;
std::元组tpl;
模板
constexpr auto as_ref_impl(元组t,std::index_序列){
//返回std::tuple_cat(std::tie(std::get(t))…);
返回std::make_tuple(std::ref(std::get(t))…);
}
模板
constexpr自动作为参考(std::tuple&t){
返回为_ref_impl(t,std::index_sequence_for{});
}
int main(){
使用std::cout;
auto-ref_-tpl=std::tuple_cat(std::tie(a),as_-ref(tpl));
//按预期打印1 2 3。
cout这是一个简单的打字错误:
constexpr auto as_ref_impl(元组t,std::index_序列){
元组
是按值获取的,因此创建本地副本,并相对于它进行引用
您应该通过引用获取Tuple
constepr auto as_ref_impl(元组&t,std::index_序列){
您的需要引用元组
参数,否则将std::ref
带到函数本地。这解释了tpl
中未修改的值和ref\tpl
中的垃圾值
改为这样做:
template <class Tuple, size_t... Is>
// note the reference parameter
constexpr auto as_ref_impl(Tuple &t, std::index_sequence<Is...>) {
return std::make_tuple(std::ref(std::get<Is>(t))...);
}
模板
//请注意参考参数
constexpr auto as_ref_impl(Tuple&t,std::index_sequence){
返回std::make_tuple(std::ref(std::get(t))…);
}
这是一个。哈哈,谢谢。真不敢相信我在这上面花了整整一个小时!
template <class Tuple, size_t... Is>
// note the reference parameter
constexpr auto as_ref_impl(Tuple &t, std::index_sequence<Is...>) {
return std::make_tuple(std::ref(std::get<Is>(t))...);
}