有没有办法让编译器在我放置字符串而不是 nlohmann::json 对象时抛出错误?
Is there a way to make the compiler throw an error whenever I put a string instead of a nlohmann::json object?
我遇到这种情况,我的方法需要一个nlohmann::json对象作为参数。
class MyClass {
public:
MyClass();
~MyClass();
bool parse(const nlohmann::json& configuration);
};
我目前给出 JSON 的方法很好,是下一个:
std::string filePath = "../folder/folder/file.json"
std::ifstream file(filePath);
nlohmann::json configJSON = nlohmann::json::parse(file);
MyClass object;
object.parse(configJSON);
我的问题是编译器接受下一段代码,但我希望它区分std::string
和nlohmann::json
,以确保我传递的是 JSON 已经解析的对象而不是随机字符串。
std::string filePath = "../folder/folder/file.json"
MyClass object;
object.parse(filePath);
然后在 parse 方法中,当我启动程序时,我收到运行时错误,因为我当然试图以不可能的方式访问字符串。
有没有办法在代码中或在 CMakeList 中使用编译标志.txt做到这一点?
您可以添加已删除的重载:
class MyClass {
public:
MyClass();
~MyClass();
bool parse(const nlohmann::json& configuration);
bool parse(const std::string&) = delete;
// bool parse(const char*) = delete; // Else you would have ambiguous call error message
};
相关文章:
- 在c++中使用nlohmann从类到json的转换
- nlohmann-json将一个数组插入到另一个数组中
- JSON转换为nlohmann JSON-lib中的结构数组
- NLOHMANN 的 JSON 库将数组转换为结构向量
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 如何在 nlohmann 的 json 库中获取数组长度?
- 有没有办法让编译器在我放置字符串而不是 nlohmann::json 对象时抛出错误?
- 为什么 nlohmann/json 序列化 "null" 而不是在 double 上"0"?
- 如何将派生类从基 ptr 分配给 nlohmann::json
- nlohmann/json uWebsocket
- std::string 可以作为 nlohmann::json 传递给显式构造函数
- 使用 NLOHMANN JSON 在 C++ 中创建嵌套的 JSON 对象
- 如何使用 nlohmann/json.hpp 序列化 2 个集合
- C++ nlohmann JSON 获取数组名称
- Nlohmann 在不知道密钥的情况下解析 JSON 文件
- Json Serialize Vector to json<Class> array (nlohmann/json.hpp)
- 为什么我不能使用 [] 运算符访问 nlohmann C++ JSON 库中的数组?
- 使用Nlohmann JSON将JSON数据保存在文件中时获取空值
- C :在项目中使用Nlohmann JSON
- C 在较旧的JSON :: NLOHMANN库中使用push_back时无匹配函数