Probleme bei der Spezialisierung von Template-Funktionen
-
Hi! hab folgendes Stück Code:
class ConfigFile { // Zeile 38 public: ConfigFile(const string& path); ~ConfigFile() {}; void save(const string& newFilename=""); template<class T> bool get(const string& key, T* returnValue); template<> bool get<>(const string& key, string* returnValue); // Zeile 45 template<> bool get<>(const string& key, char* returnValue); void set(const string& key, const string& value); private: void readSettings(); string filepath_; map<string, string> settings_; static const char COMMENT_SIGN = '#'; static const char ASSIGN_SIGN = '='; };
ConfigFile::get() ist eine Template-Funktion mit Spezialisierungen für Pointer auf strings und chars...
mit dem BCC32 compiliert der Code problemlos (und funktioniert auch
), der GCC aber meldet bei der Deklaration der ersten Spezialisierung:
45 E:\works\coding\cpp\blueScreen_Saver\src\ConfigFile.h explicit specialization in non-namespace scope `class ConfigFile' 45 E:\works\coding\cpp\blueScreen_Saver\src\ConfigFile.h invalid use of undefined type `class ConfigFile' 38 E:\works\coding\cpp\blueScreen_Saver\src\ConfigFile.h forward declaration of `class ConfigFile'
Wo liegt der Fehler??? sollte der GCC nicht naeher am Standard sein als der BCC? Oder hab ich irgendwo was uebersehen?
-
Oder hab ich irgendwo was uebersehen?
Ja. Standard-C++ erlaubt Spezialisierungen nur im Namespacescope nicht aber im Klassenscope.
Du musst die Spezialisierungen also aus der Klassendefinition rausziehen:class ConfigFile { // Zeile 38 public: ConfigFile(const string& path); ~ConfigFile() {}; void save(const string& newFilename=""); template<class T> bool get(const string& key, T* returnValue); void set(const string& key, const string& value); private: void readSettings(); string filepath_; map<string, string> settings_; static const char COMMENT_SIGN = '#'; static const char ASSIGN_SIGN = '='; }; template<> bool ConfigFile::get(const string& key, string* returnValue) { ... } template<> bool ConfigFile::get(const string& key, char* returnValue) { ... }
Ich würde hier allerdings eher Überladung verwenden:
class ConfigFile { // Zeile 38 public: ... template<class T> bool get(const string& key, T* returnValue); bool get(const string& key, string* returnValue); bool get(const string& key, char* returnValue); ... };
-
HumeSikkins schrieb:
Oder hab ich irgendwo was uebersehen?
Ja. Standard-C++ erlaubt Spezialisierungen nur im Namespacescope nicht aber im Klassenscope.
[...]
Ich würde hier allerdings eher Überladung verwenden:
Dankeschoen...
Ich versteh zwar jetzt die Erklaerung ehrlich gesagt nicht so ganz
aber es funktioniert
Warum wuerdest du eher Ueberladung verwenden? Das ist doch eigentlich ein typisches Biespiel von Spezialisierung von Template-Funktionen
-