std :: make_tuple不会引用 [英] std::make_tuple doesn't make references

查看:782
本文介绍了std :: make_tuple不会引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试 std :: tuple 结合参考:

I've been experimenting with std::tuple in combination with references:

#include <iostream>
#include <tuple>

int main() {
  int a,b;
  std::tuple<int&,int&> test(a,b);
  std::get<0>(test) = 1;
  std::get<1>(test) = 2;
  std::cout << a << ":" << b << std::endl;

  // doesn't make ref, not expected
  auto test2 = std::make_tuple(a,b);
  std::get<0>(test2) = -1;
  std::get<1>(test2) = -2;
  std::cout << a << ":" << b << std::endl;

  int &ar=a;
  int &br=b;
  // why does this not make a tuple of int& references? can we force it to notice?
  auto test3 = std::make_tuple(ar,br);
  std::get<0>(test3) = -1;
  std::get<1>(test3) = -2;
  std::cout << a << ":" << b << std::endl;
}

在这三个示例中,前两个工作按预期工作。第三个但不是。我期待 auto 类型( test3 )与 test类型相同(即 std :: tuple< int&,int&> )。

Of the three examples here the first two work as expected. The third one however does not. I was expecting the auto type (test3) to be the same as the type of test (i.e. std::tuple<int&,int&>).

看来 std :: make_tuple 不能自动生成引用的元组。为什么不?我可以做什么来做这种情况,除了显式地构造这种类型的东西我自己?

It seems that std::make_tuple can't automatically make tuples of references. Why not? What can I do to make this the case, other than explicitly constructing something of that type myself?

(编译器是g ++ 4.4.5,使用4.5不会更改

(Compiler was g++ 4.4.5, using 4.5 doesn't change it)

推荐答案

请尝试 forward_as_tuple

auto test3 = std::forward_as_tuple(ar,br);

这篇关于std :: make_tuple不会引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆