Skip to content

std::optional not working with primitive types #2383

Description

@ThisALV

What is the issue you have?

I'm currently trying to implement the to_json conversion function for the std::optional type. Here is the function

template<typename T> void to_json(json& data, const std::optional<T>& opt) {
    data = opt ? json(*opt) : json(nullptr);
}

But when using it with T as a primitive type, I get an compiler (and linter) error which says :

no viable overloaded '='
note: no known conversion from 'const std::optional' to 'nlohmann::basic_json<>'

But with non-primitive type, everything work as expected, as long as I define the appropriate to_json function for that non-primitive type.

Please describe the steps to reproduce the issue.

Here's a code for testing :

#include "nlohmann/json.hpp"
#include <optional>
#include <iostream>

using json = nlohmann::json;

template<typename T> struct Wrapper {
    T value;
};

template<typename T> void to_json(json& data, const Wrapper<T>& wrapper) {
    data = wrapper.value;
}

template<typename T> void to_json(json& data, const std::optional<T>& opt) {
    data = opt ? json(*opt) : json(nullptr);
}

int main() {
    const std::optional<double> i { 3.14 };
    const std::optional<Wrapper<double>> j { Wrapper<double> { 3.14 } };
    json data;

    // data["number"] = i;
    data["wrapper"] = j;

    std::cout << data << std::endl;
}

Uncomment the commented line and this code will no compile anymore, even if I declare a function like :

void to_json(json&, const double) {}

...it doesn't change anything.

What is the expected behavior?

It should convert the std::optional into json double as the to_json function for the std::optional convert either nullptr or T to json if it has a value and as double is primitively supported by NlohmannJson.

And what is the actual behavior instead?

It doesn't find any way to convert the std::optional value into json value.

Which compiler and operating system are you using?

  • Compiler: GCC 9.3.0, Clang 10.0.0 and MSVC 19.
  • Operating system: Ubuntu 20.4 LTS

Which version of the library did you use?

  • latest release version 3.9.1
  • other release - please state the version: ___
  • the develop branch

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind: bugstate: stalethe issue has not been updated in a while and will be closed automatically soon unless it is updated

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions