The following code works well on my computer:
#include <string>
#include <variant>
#include <iostream>
int main() {
std::variant<double, std::string> var;
var = 20;
if (std::get_if<0>(&var))
std::cout << "a double\n";
else if (std::get_if<1>(&var))
std::cout << "a string\n";
return 0;
}
I create a variant
containing either a double
or a string
and then check if the variant holds an element of either type using std::get_if through an index. In constrast, the following code does not compile:
#include <string>
#include <variant>
#include <iostream>
int main() {
std::variant<double, std::string> var;
var = 20;
for (size_t i = 0; i < 2; ++i) {
if (std::get_if<i>(&var))
std::cout << i;
}
return 0;
}
I am still trying to learn c++
, and the documentation is at times still incomprehensible to me.
Can somebody kindly explain how the documentation I linked informs me that I cannot use a size_t
(or an int
) element to check if the variant holds a particular type?
Second, is there a way to check type membership of a variant in a loop at all?