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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With