0

I'm trying to assign a float to a defined value in my std::map using std::variant. I initialized my map this way:

std::map<std::string,std::variant<float,int,bool,std::string> kwargs; 
kwargs["type"] = "linear"; 
kwargs["flag"] = true; 
kwargs["height"] = 5; 
kwargs["length"] = 4.5; 

I'm trying to archive this operation:

float f = kwargs["length"]; 
float a = f+0.5; 

How can I transfer std::map key into a float for simple arithmetic operation?

  • You are assigning _from_ the `variant`, not to it. So, its assignment operator is irrelevant. You just need to read how to get the desired value, which of course requires telling the compiler _which_ type you want. – underscore_d Jul 03 '20 at 14:42

2 Answers2

1

Try using std::get like this:

 const float f = std::get<float>(kwargs["length"]);

You can see the docs here: https://en.cppreference.com/w/cpp/utility/variant/get

Buddy
  • 10,874
  • 5
  • 41
  • 58
  • Then it sounds like your variant does not currently contain a `float`. So you should check the docs to see how to check what type it contains, or how to get the contained value or a default if that is not the current type. This all comes down to reading the docs. Or, if you want help with code, post the specific code, rather than making us assume where in the previous code you added this line here. – underscore_d Jul 03 '20 at 14:47
1

To access the variant, you need to use the free function std::get:

float f = std::get<float>(kwargs["length"]);

Also, you might run into a problem with this line:

kwargs["length"] = 4.5; 

Since 4.5 is a literal of type double, and not float. To solve this, just use the F suffix:

kwargs["length"] = 4.5F;