I already know how to use std::variant
fairly well with std::get_if()
, std::get()
and std::visit()
. But, what if I just want a simple way to tell if a variant has ever been initialized to any value? That is, I don't care what the value is, I just want a boolean test. How do I do that?
For example, suppose I declare a variant on the stack:
std::variant<int, double> data;
Then, my function goes on and might or might not initialize this variable. At the end of my function, I want to test if it was initialized.
- I looked at the
index()
function. That returns 0 both for an uninitialized variant and for one I initialize to the first type declared. - I looked at the
valueless_by_exception()
function but that returns false whether I initialize the variant or not.
About the only thing I could think of to compare it to a default constructed one, like this:
using Data = std::variant<int, double>;
Data data;
// ... code here that might initialize data or might not...
if (data == Data())
// Not initialized
else
// Initialized
This seems to work, but reading the comments on operator==()
for std::variant
, it seems like this behavior is undefined.
So, is this a safe way to test, or is there another way?