Update: See the full answer below. The short answer is no, not directly. You can create an indirect reference using std::reference_wrapper or accomplish the same effect more generally with pointers (but without the syntactic sugar and added safety of references).

I ask because tuples make a convenient variadic storage unit in C++11. In theory it sounds reasonable for one element of a tuple to hold a reference to another element in the same tuple. (Replace "reference" with "pointer" and it works in practice.) The devil is the details of constructing such a tuple. Consider the following example:

#include <tuple>
#include <iostream>

class A
{
public:
  A() : val(42) { }
  int val;
};

class B
{
public:
  B(A &a) : _a(a) { }
  int val() { return _a.val; }

private:
  A &_a;
};

int main()
{
  A a;
  B b(a);
  std::tuple<A, B> t1(a, b);
  a.val = 24;
  std::cout << std::get<0>(t1).val << "\n"; // 42
  std::cout << std::get<1>(t1).val() << "\n"; // 24

  return 0;
}

The second element in the tuple t1 references the automatic variable a instead of the first element in t1. Is there any way to construct a tuple such that one element of the tuple could hold a reference to another element in the same tuple? I'm aware that you could sort of achieve this result by creating a tuple of references, like this:

int main()
{
  A a;
  B b(a);
  std::tuple<A &, B &> t2 = std::tie(a, b);
  a.val = 24;
  std::cout << std::get<0>(t2).val << "\n"; // 24
  std::cout << std::get<1>(t2).val() << "\n"; // 24

  return 0;
}

But for my purposes that's cheating, since the second element in t2 is still ultimately referencing an object that lives outside of the tuple. The only way I can think of doing it compiles fine but may cont

Edit
Report