Reputation: 373
I use boost::variant for storage and one possible data member is a large struct. So the size of the binary variant is at least this struct size. All other members are very small like int or double in my case. To avoid the basic large layout is there a way to force boost::variant to store the item as pointer ? Of course I could use a smart pointer to store this large struct but in this case the get Methode would also work as an pointer access .. this is not so nice
boost::variant<int,double,large_struct>>
Size of 500 bytes
Or the other small solution but each access has to deal with the pointer
boost::variant<int,double,shared_ptr<large_struct>
Sizeof 40 Bytes
Upvotes: 4
Views: 402
Reputation: 16204
Yes, you can declare the variant as
boost::variant<int,double,boost::recursive_wrapper <large_struct>>>
Recursive wrapper is normally used for the case that large_struct
is an incomplete type at the time that you declare the variant. For instance, what if this variant needs to be a member of large_struct
.
recursive_wrapper<T>
is internally just a pointer T*
, but the variant is aware of this pointer and transparently dereferences it for you. This is for when the fact that it needs to be a pointer is a "detail" that you don't want the user to have to think about.
It works perfectly for your use case though. Using recursive_wrapper<large_struct>
instead of large_struct
makes the large_struct
instance live on the heap, but gives exactly the same interface and usage as if there were no recursive wrapper.
Upvotes: 3