首页 > 解决方案 > std::string 可以作为 nlohmann::json 传递给显式构造函数

问题描述

为什么以下代码编译,即使我将对象传递给std::string需要(到库)对象的显式构造函数?我的理解是不会因为关键字而被隐式转换。是否可以更改我的代码,使其仅在通过 a 时才能编译成功?nlohmann::json std::stringexplicitnlohmann::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);
}

标签: c++nlohmann-json

解决方案


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

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

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

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

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

推荐阅读