Reputation: 796
I have created a function template for loading my settings from a binary file.
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;
};
I would like to be able to invoke the function and return the appropriate settings class.
Coming from C# I would do the following.
MySettingsClass settings = LoadSettings<MySettingsClass>("FileName.bin");
How can I do the same thing in C++?
EDIT:
I should be more generic!
throw std::runtime_error("Failed to parse " + typeid(T).name());
Upvotes: 0
Views: 142
Reputation: 16148
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");
}
This should work, however you might want to consider writing an extraction operator foe your types T.
Upvotes: 0
Reputation: 5546
Then use this syntax in C++
MySettingsClass settings = LoadSettings<MySettingsClass>(std::string("FileName.bin"));
Upvotes: 1