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

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

即使我将 std::string 对象传递给需要 nlohmann::json [=19= 的 explicit 构造函数,为什么以下代码仍能编译] 目的?我的理解是 std::string 不会由于 explicit 关键字而被隐式转换。 是否可以更改我的代码,使其仅在传递 nlohmann::json 时编译成功?

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

#include <nlohmann/json.hpp>

struct A {
    explicit A(nlohmann::json json) {

    }
};

int main() {
    std::string a = "hello";
    A b(a);
}

Why does the following code compile, even though I am passing a std::string object to a explicit constructor which expects a nlohmann::json (to the library) object? My understanding is that std::string won't be implicit converted due to the explicit keyword.

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

Is it possible to change my code so that it will compile successful only when a nlohmann::json is passed?

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

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