std::string 可以作为 nlohmann::json 传递给显式构造函数
std::string can be passed as nlohmann::json to explicit constructor
为什么下面的代码可以编译,即使我将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} ;
}
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 在c++中使用向量时,如何调用构造函数和析构函数
- std::string 可以作为 nlohmann::json 传递给显式构造函数