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 :)