I am making a few classes which allocates a lot of memory. Therefore, I need to minimize the number of copy operations.
While working on it, I wished that if I had a template class that contains a type(T) or a reference(T&), not both, so that I could make a code like below:
template<typename T>
class EITHER {
/* some code */
};
class A { /* some code */ };
void f(A &a) { /* some code changing `a` */ }
int main() {
A a(42);
std::vector<EITHER<A>> v;
v.emplace_back(a); /* stored as a reference */
v.emplace_back(A(72)); /* stored as a value (possibly moved) */
f(a); /* okay. */
f(v[0]); /* okay, modifies `a` through a reference stored in `EITHER<A>`. */
f(v[1]); /* okay, modifies the value stored in `EITHER<A>`. */
{
A b(3);
v.emplace_back(b); /* stored as a reference */
} // Now `b` is destructed, `v[2]` holds the latest value (not reference) of `b`.
f(v[2]); /* okay, modifies the value stored in `EITHER<A>`. */
}
I'm pretty sure this will be useful in many cases, but I have no idea how to implement this.
std::variantcannot store references.std::optional<T>withT*might do the job, but I'm pretty sure there should be a way to handle this likestd::optional. Ifstd::optionalstores or does not store the type,EITHERwill store only the typeTor the typeT&.- Lastly, it seems like I have to memo if the original variable is destructed or not, but will it be possible without modifying
A?
Please remember that there are finitely many classes that EITHER will be applied, if this is useful.
I wish I could get any solution or a feedback for this question. Thanks.
p.s. Aiming c++20.