I'm still trying to update my older programs to modern C++, and I have another question related to templates. I'm using libconfig++ to handle program configuration, writing plain text data to a configuration file. You can choose the type of data you want to write to the file, and the library uses an enum to do this (ie Setting::TypeString, Setting::TypeBoolean, etc.)
At first, I used plain overloading as you can see below :
void Config::write_value(Setting& root, const string& key, const string& value) {
if (!root.exists(key.c_str())) root.add(key.c_str(), Setting::TypeString) = value;
else {
Setting& s = root[key.c_str()];
s = value;
}
}
void Config::write_value(Setting& root, const string& key, const bool value) {
if (!root.exists(key.c_str())) root.add(key.c_str(), Setting::TypeBoolean) = value;
else {
Setting& s = root[key.c_str()];
s = value;
}
}
But these functions are candidates for a generic treatment, as just one parameter changes, and the type used by the library can be deduced from the parameter.
The question is : how can I do it ? I tried using conditional_t and is_same, but the compiler isn't happy about what I tried, something's wrong and I think it's related to the enum ...
What's the right way to map the enum to the parameter type ?
Here's one (of numerous) thing I tried :
template<typename T>
using Type = std::conditional_t<std::is_same_v<T, bool>, Setting::TypeBoolean, void>;
template<typename T>
void write_value(libconfig::Setting& root, const std::string& key, const T& value)
{
if (!root.exists(key.c_str())) root.add(key.c_str(), Type<T>) = value;
else {
Setting& s = root[key.c_str()];
s = value;
}
}
// Compiler error :
error C2275: 'Config::Type<bool>' : illegal use of this type as an expression
Thanks for reading me :)
Edit Setting::* is an enum, defined as Setting::Type actually.
enum Type
{
TypeNone = 0,
// scalar types
TypeInt,
TypeInt64,
TypeFloat,
TypeString,
TypeBoolean,
// aggregate types
TypeGroup,
TypeArray,
TypeList
};
Setting::*is not a type, since it is passed as an argument to the function. What is it?