I am trying to assign a value to a simple std::variant
#include <variant>
using namespace std;
int main()
{
variant<int, double> v;
v = 12; //error
v = 12.0; //error
}
I expect this to compile, with
g++ main.cpp
but I get this error:
no operator "=" matches these operands -- operand types are: std::variant<int, double> = int
I tried replacing it with a union
, but the union only works if I specify the field to write in, like this:
union number {
int i;
double d;
};
int main()
{
number n;
n.i = 10; //OK
n = 2.5; //error
}
How do I correctly assign a variant?
my system's current g++ version:
g++ --version
g++ (Ubuntu 9.3.0-10ubuntu2) 9.3.0
You have to pass the C++ standard to the compiler with
g++ -std=c++17 main.cpp
The default standard of gcc 9.3.0 is C++14 which doesn't support variant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With