1

I have a std::optional<float> test;

I want to store this value to json file, and since it is optional, I donot know until runtime, if the variable has a value or not. So I am trying to do this

frameJson["Test"] = test.has_value() ? test.value() : std::nullopt;

But I get this error -

Error:Incompatible operand types ('const std::optional<float>::value_type' (aka 'const float') and 'const std::nullopt_t')

Question - How do I store the value of std::optional to json in all cases, meaning if its empty, then it has to be null or something meaningful.

Nitron_707
  • 307
  • 4
  • 10
  • 1
    You might handle `std::nullopt` in 2 ways in json, with `null` value, or with absent key. – Jarod42 Jul 30 '23 at 11:48
  • @n.m.couldbeanAI I see, so you basically remove the `{"Test":value}` itself from json, so that parsing doesnt give undefined value – Nitron_707 Jul 30 '23 at 11:49
  • 1
    Sorry has a botched edit and deleted a comment. I mean, you can not store any value, *or* store `nullptr`, *or* store an empty `json` object. But you cannot do that with a ternary operator. Use a plain old `if`. – n. m. could be an AI Jul 30 '23 at 11:55
  • @n.m.couldbeanAI, yes got the first time itself, avoid adding the object to file if `has_value()` is false, which I think will work in my case – Nitron_707 Jul 30 '23 at 12:05
  • @Jarod42 absent key works as well, thanks – Nitron_707 Jul 30 '23 at 12:15

1 Answers1

1

How about

frameJson["Test"] = test.has_value() ? basic_json(test.value()) : basic_json();
jpalecek
  • 47,058
  • 7
  • 102
  • 144