14

The following code compiles and does the "right thing" :

#include <boost/variant.hpp>
#include <iostream>

int main()
{
  int a = 10;
  boost::variant<int&, float&> x = a;
  a = 20;
  std::cout << boost::get<int&>(x) << "\n";
  return 0;
}

How does boost::variant store a reference? According to C++ standard, how references are stored is completely up to the compiler. Actually, how does boost::variant even know how many bytes is taken up by a reference? sizeof(T&) == sizeof(T), so it can't be using sizeof() operator. Now, I know references are most probably implemented as pointers, but there is no guarantee in the language. A good explanation of how get<> and visitation works when the variant is storing references get extra points :)

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
keveman
  • 8,427
  • 1
  • 38
  • 46

1 Answers1

7

You can declare struct fields as references.

struct ref_to_int {
    ref_to_int(int& init)
      : _storage(init) {} // _storage stores the reference.
private:
    int& _storage;
};

You can take the sizeof(ref_to_int), which is 8 on my x64 with gcc. The field stores the reference.

Laurent LA RIZZA
  • 2,905
  • 1
  • 23
  • 41