I want to define a struct, e.g. type
, such that sizeof(type)
is no less than some value.
Motivation:
I have a vector std::vector<type>
and I will remove some elements from it. Also, I have saved the indexes of some elements to other places, thus I want just mark it as not used and reuse it in the future. This leads me to save the next available position as a list in erased positions. As a result, sizeof(type)
should be no less than sizeof(size_t)
and type
should be properly aligned as well.
Possible Solutions:
boost::variant<type, size_t>
This has two problems from my point of view. If I
use boost::get<type>
, the performance will decrease significantly. If I useboost::apply_visitor
, the syntax would be weird and the performance also decreases according to my profile.union{type t; size_t s;}
This of course works except for two shortfalls. Firstly, the syntax to refer the member of
type
would be more messy. Secondly, I have to define constructor, copy constructor, etc. for this union.Extend
type
bychar[sizeof(size_t) - sizeof(type)]
This almost fulfills my requirements. However, this risks of zero length array which is not supported by the c++ standard and possibly wrong alignment.
Since I won't use type
as size_t
often, I'd like to just ensure I can use reinterpret_cast<size_t>
when needed.
Complements
After reading the comments, I think the best solution for my problem should be boost::variant
. But I am still wondering is there a way to combine the benefits of solution 2 and 3, i.e.
a. I can access members of type
without changes.
b. Get the guarantee that reinterpret_cast<size_t>
works.