簡體   English   中英

std::string 可以作為 nlohmann::json 傳遞給顯式構造函數

[英]std::string can be passed as nlohmann::json to explicit constructor

為什么即使我將std::string對象傳遞給需要nlohmann::json (到庫)對象的顯式構造函數,以下代碼nlohmann::json 我的理解是std::string不會由於explicit關鍵字而被隱式轉換。 是否可以更改我的代碼,使其僅在通過nlohmann::jsonnlohmann::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::jsonnlohmann::json成功編譯?

您可以通過非常量引用傳遞參數,防止編譯器傳遞隱式創建的臨時對象:

struct A {
    explicit A(nlohmann::json &json) {
    }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM