nlohmann json ambiguous overload for 'operator='

情到浓时终转凉″ 提交于 2019-12-11 05:48:54

问题


I'm getting this compilation error with the following code

#include <iostream>
#include <boost/optional.hpp>
#include "nlohmann_json.hpp"

namespace nlohmann {
template <typename T>
struct adl_serializer<boost::optional<T>> {
  static void to_json(json& j, const boost::optional<T>& opt) {
    if (opt == boost::none) j = nullptr;
    else j = *opt;
  }
  static void from_json(const json& j, boost::optional<T>& opt) {
    if (j.is_null()) opt = boost::none;
    else opt = j.get<T>();
  }
};
}

int main(int argc, char* argv[]) {

  nlohmann::json json;
  boost::optional<std::string> str = json["str"]; // works
  // boost::optional<std::string> str;
  // str = json["str"]; // doesn't work

}

The full error message is

nlohmann.cc: In function 'int main(int, char**)':
nlohmann.cc:24:19: error: ambiguous overload for 'operator=' (operand types are 'boost::optional<std::__cxx11::basic_string<char> >' and 'nlohmann::basic_json<>::value_type {aka nlohmann::basic_json<>}')
   str = json["str"];
                   ^
In file included from /opt/gcc-7.2.0/include/boost/optional.hpp:15:0,
                 from nlohmann.cc:2:
/opt/gcc-7.2.0/include/boost/optional/optional.hpp:1019:15: note: candidate: boost::optional<T>& boost::optional<T>::operator=(const boost::optional<T>&) [with T = std::__cxx11::basic_string<char>]
     optional& operator= ( optional const& rhs ) = default;
               ^~~~~~~~
/opt/gcc-7.2.0/include/boost/optional/optional.hpp:1031:15: note: candidate: boost::optional<T>& boost::optional<T>::operator=(boost::optional<T>&&) [with T = std::__cxx11::basic_string<char>]
     optional& operator= ( optional && ) = default;
               ^~~~~~~~
/opt/gcc-7.2.0/include/boost/optional/optional.hpp:1078:15: note: candidate: boost::optional<T>& boost::optional<T>::operator=(boost::none_t) [with T = std::__cxx11::basic_string<char>]
     optional& operator= ( none_t none_ ) BOOST_NOEXCEPT

What is the difference between the two assignment operator use cases? Why does the second one not work?

I'm using GCC 7.2.0, with -std=c++14.

来源:https://stackoverflow.com/questions/50881469/nlohmann-json-ambiguous-overload-for-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!