有没有办法让编译器在我放置字符串而不是 nlohmann::json 对象时抛出错误?

Is there a way to make the compiler throw an error whenever I put a string instead of a nlohmann::json object?

本文关键字:json nlohmann 对象 错误 出错 编译器 字符串 有没有      更新时间:2023-10-16

我遇到这种情况,我的方法需要一个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::stringnlohmann::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
};