![](/img/trans.png)
[英]How to get number as std::string through nlohmann::json parsing?
[英]std::string can be passed as nlohmann::json to explicit constructor
為什么即使我將std::string
對象傳遞給需要nlohmann::json
(到庫)對象的顯式構造函數,以下代碼nlohmann::json
? 我的理解是std::string
不會由於explicit
關鍵字而被隱式轉換。 是否可以更改我的代碼,使其僅在通過nlohmann::json
時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
(到庫)對象的顯式構造函數,以下代碼nlohmann::json
? 我的理解是std::string
不會由於explicit
關鍵字而被隱式轉換。
A
構造函數中的explicit
僅意味着必須顯式調用A
構造函數(您就是這樣)。 編譯器在將參數傳遞給A
構造函數時允許使用隱式轉換,除非它們使用本身也是explicit
類型( nlohmann::json
構造函數不是)。
是否可以更改我的代碼,使其僅在通過
nlohmann::json
時nlohmann::json
成功編譯?
您可以通過非常量引用傳遞參數,防止編譯器傳遞隱式創建的臨時對象:
struct A {
explicit A(nlohmann::json &json) {
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.