簡體   English   中英

功能模板-根據輸入類返回T嗎? -C ++

[英]Function template - Returning T based on input class? - C++

我已經創建了一個功能模板,用於從二進制文件加載設置。

template<class T> T LoadSettings(const std::string &fileName)
{
    // Load settings
    T settings;

    std::string filePath(LOCAL_FILE_DIR);
    filePath.append(fileName);

    std::ifstream file(filePath, std::ios::in | std::ios::binary);

    if (file.is_open())
    {
        if (!settings.ParseFromIstream(&file)) 
        {
            throw ExceptionMessage("Failed to parse TextureAtlasSettings");
        }
    }
    else
    {
        throw ExceptionMessage("Failed to open file");
    }

    return settings;
};

我希望能夠調用該函數並返回適當的設置類。

來自C#,我將執行以下操作。

MySettingsClass settings = LoadSettings<MySettingsClass>("FileName.bin");

如何在C ++中做同樣的事情?

編輯:

我應該更通用!

throw std::runtime_error("Failed to parse " + typeid(T).name());

然后在C ++中使用此語法

MySettingsClass settings = LoadSettings<MySettingsClass>(std::string("FileName.bin"));
 template<typename T> 
 T LoadSettings(const std::string& fileName)
 {
    // Load settings
    T settings;

    std::string filePath(LOCAL_FILE_DIR);
    filePath += fileName; 

     std::ifstream file(filePath, std::ios::in | std::ios::binary); 

     if (file && settings.ParseFromIstream(file)) 
     {    
           return settings;
     }
     throw std::runtime_error("Failed to parse TextureAtlasSettings");
 }

這應該可行,但是您可能要考慮針對類型T編寫一個提取運算符。

暫無
暫無

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

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