std::string 可以作为 nlohmann::json 传递给显式构造函数

std::string can be passed as nlohmann::json to explicit constructor

本文关键字:构造函数 json nlohmann string std      更新时间:2023-10-16

为什么下面的代码可以编译,即使我将std::string对象传递给一个显式构造函数,该构造函数需要一个nlohmann::json(到库(对象?我的理解是,std::string不会因为explicit关键字而隐式转换。 是否可以更改我的代码,以便仅在传递nlohmann::json时成功编译?

我在调试模式下使用Visual Studio 2019,/Wall

#include <nlohmann/json.hpp>
struct A {
explicit A(nlohmann::json json) {
}
};
int main() {
std::string a = "hello";
A b(a);
}

为什么下面的代码要编译,即使我将std::string对象传递给一个显式构造函数,该构造函数需要一个nlohmann::json(到库(对象?我的理解是,std::string不会因为关键字explicit而隐式转换。

A构造函数中的explicit只是意味着必须显式调用A构造函数(您就是(。允许编译器在将参数传递给A构造函数时使用隐式转换,除非它们使用本身也explicit的类型(nlohmann::json构造函数不是(。

是否可以更改我的代码,使其仅在传递nlohmann::json时才能成功编译?

您可以通过非常量引用传递参数,防止编译器传递隐式创建的临时对象:

struct A {
explicit A(nlohmann::json &json) {
}
};

这可能是矫枉过正,但以下内容似乎有效,同时还允许将 const 引用作为构造函数参数:

#include <nlohmann/json.hpp>
#include <type_traits>
struct A {
template<typename T, typename = std::enable_if_t<std::is_same_v<T, nlohmann::json>>>
explicit A(const T& json) {
}
};
int main() {
const std::string a = "hello";
// A b(a); // ERROR

const auto json_val = nlohmann::json::parse("{}") ;
A c {json_val} ;
}