Lou
Lou

Reputation: 21

using std::variant with a vector

I'm writing a program that uses a variant in a vector and I encoutred a problem saying:

E0413   no suitable conversion function from "std::variant<char, short>" to "char" exists

this is my program:

int main()
{
   
   std::vector<std::variant<char, short>> vec;
   switch(type)
   {
     case 1200: //char
       char tab[10];
       for(unsigned i = 0; i<6; i++)
           tab[i] = vec.at(i);
     case 1300: //short
       short tab[10];
       for(unsigned i = 0; i<6; i++)
           tab[i] = vec.at(i);
   }
 return 0;
}

I used std::variant because type distinction is needed.

how could I solve this?

thank you

Upvotes: 1

Views: 11068

Answers (2)

mediocrevegetable1
mediocrevegetable1

Reputation: 4207

       char tab[10];
       for(unsigned i = 0; i<6; i++)
           tab[i] = vec.at(i);

You need to explicitly specify which type of the variant you want to take. For this, you can use std::get:

       char tab[10];
       for(unsigned i = 0; i<6; i++)
           tab[i] = std::get<char>(vec.at(i)); // std::get<0>(vec.at(i)) would have the same effect

Upvotes: 6

Guy Marino
Guy Marino

Reputation: 439

Use std::get<char>(variant) instead of implicit conversion.

Upvotes: 1

Related Questions