c++ - std::string 可以作为 nlohmann::json 传递给显式构造函数
问题描述
为什么以下代码编译,即使我将对象传递给std::string
需要(到库)对象的显式构造函数?我的理解是不会因为关键字而被隐式转换。是否可以更改我的代码,使其仅在通过 a 时才能编译成功?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
关键字而被隐式转换。
构造函数explicit
中的A
只是意味着A
必须显式调用构造函数(您就是这样)。编译器在将参数传递给构造函数时允许使用隐式转换A
,除非它们使用explicit
本身也是类型(nlohmann::json
构造函数不是)。
是否可以更改我的代码,使其仅在
nlohmann::json
通过 a 时才能编译成功?
您可以通过非常量引用传递参数,从而防止编译器传递隐式创建的临时对象:
struct A {
explicit A(nlohmann::json &json) {
}
};
推荐阅读
- algorithm - 给定一棵树,计算这棵树中的最长路径,其路径中的节点具有相同的设置位
- java - 尝试在空对象引用上调用虚拟方法。数组列表
- wordpress - 为什么结帐页面上的点击事件不起作用?
- json - 如何在 kotlin 中将 Json 数据解析为 tablayout?
- sql - 如何在 oracle 的功能索引中创建分区?
- c# - 使用给定的测试套件找出在 C# 源代码中执行的行(获取代码覆盖率)
- python - 使用 imshow 绘制单通道图像(例如灰度)时出现问题
- r - 将大列表转换为一列包含所有元素的小标题
- node.js - 在不使用数据库的情况下为服务编写单元测试
- python - Pytorch中[-1,0]的维度范围是多少?