Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a value to std::variant? [duplicate]

Tags:

c++

c++17

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
like image 965
tornikeo Avatar asked Sep 17 '25 18:09

tornikeo


1 Answers

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.

like image 64
Thomas Sablik Avatar answered Sep 19 '25 10:09

Thomas Sablik