3

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
tornikeo
  • 915
  • 5
  • 20
  • 4
    Are you sure you are using a C++17 and above compiler? – Bathsheba Sep 02 '20 at 10:50
  • 2
    Cannot reproduce: your original code seems to me correct. – max66 Sep 02 '20 at 10:50
  • Just made an edit – tornikeo Sep 02 '20 at 10:55
  • A one-liner to check which C++ Standard your g++ version defaults to: `echo __cplusplus | g++ -E -x c++ - | tail -n 1`. Yours will probably [be `201402L`](https://stackoverflow.com/a/26089678/1171191). – BoBTFish Sep 02 '20 at 11:03
  • You should have read the complete output of the compiler, starting from the very first error: `test.cpp:7:5: error: ‘variant’ was not declared in this scope` and the following `note: ‘std::variant’ is only available from C++17 onwards` – Ruslan Sep 02 '20 at 12:17

1 Answers1

2

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.

Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62