Ich und Templates werden wohl nie ganz Freunde werden ... Ich habe, grob zusammengefasst folgenden Code:
|
C-/C++-Quelltext
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
//! Returns a key as a specific type whilst performing the conversion via a stringstream.
/*! This will only work for C++ basic types, not for user defined ones! */
template<typename T>
T getKeyAs(const std::string& section, const std::string& key)
{
// Making sure the field exists
if (!hasKey(section, key))
{
// No key or no section?
if (!hasSection(section))
throw (std::out_of_range("Could not find section \"" + section + "\""));
else
throw (std::out_of_range("Could not find key \"" + key + "\""));
}
// Convert the value
std::istringstream stream(mSettings[section][key]);
T ret;
stream >> ret;
return (ret);
}
|
Dieser code sucht aus einer geschachtelten Map (für Sektionen und einzelne Wert) einen Wert raus, jagt ihn durch einen stringstream und erlaubt es mir so, die meisten grundlegenden C++ Typen sehr komfortabel aus meiner Config Klasse zu ziehen.
Dieses System versagt aber (naheliegenderweise), wenn ich einen boolschen Wert auslesen möchte, da ich boolsche Werte als string in der .cfg hinterlege. Also in etwa so:
|
Quellcode
|
1
2
|
[MySection]
somebool = true
|
Jetzt könnte ich natürlich auf 0 und 1 ausweichen, aber ich find die "Textvariante" schon schöner. Also wollte ich das Template folgendermaßen spezialisieren:
|
C-/C++-Quelltext
|
1
2
3
4
5
6
7
8
9
10
|
template<>
bool getKeyAs<bool>(const std::string& section, const std::string& key)
{
// Retrieve the value of the key and transform it to lowercase
std::string value = getKey(section, key);
std::transform(value.begin(), value.end(), value.begin(), tolower);
// Everything nonzero or "true" means true
return (value != "0" || value == "true");
}
|
Nur leider wird diese Spezialisierung nie aufgerufen. Google spuckt mir wenn ich nach
C++ Template Method Specialisation suche immer nur relativ fortgeschrittene Themen aus (Partial specialisation etc).
Aber ich vermute fast, dass der Fehler irgendwo winzigklein in meinem Code steckt ...
Edit: Autsch, das tut er ... Der gcc kompiliert das nichtmal