我使用以下代码
收到此编译错误#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
}
完整的错误消息是
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
两个赋值运算符用例有什么区别?为什么第二个不起作用?
我正在使用GCC 7.2.0,-std=c++14
。