Datentyp zur Leufzeit festlegen
-
@ BigNeal:
#include <string> #include <sstream> #include <iostream> class Type { protected: std::stringstream myStream; public: std::string getValue() const { return myStream.str(); } }; class TypeString : public Type { public: TypeString(const std::string& s) { myStream << s; } }; class TypeInt : public Type { public: TypeInt(int i) { myStream << i; } }; class TypeFloat : public Type { public: TypeFloat(float f) { myStream << f; } }; int main() { TypeInt i(10); TypeFloat f(10.5); TypeString s("Test"); std::cout << i.getValue() << std::endl; std::cout << f.getValue() << std::endl; std::cout << s.getValue() << std::endl; }Aber wo soll der Sinn sein? Mit einem std::string kann man nicht rechnen!
-
Jetzt hab ich etwas zusammengefrickelt bekommen

#include <string> #include <sstream> #include <iostream> #include <ctime> #define DECLARE_NEW_TYPE(RealType, TypeName) class TypeName : public Type { public: TypeName(RealType a) { myStream << a; myType = #TypeName; } }; class Type { protected: std::stringstream myStream; std::string myType; public: template <typename T> T getValue() { T tmp; myStream >> tmp; return tmp; } const std::string& getType() const { return myType; } }; DECLARE_NEW_TYPE(int, TypeInt) DECLARE_NEW_TYPE(float, TypeFloat) DECLARE_NEW_TYPE(std::string, TypeString) int main() { TypeInt i(10); TypeFloat f(10.5); TypeString s("lol"); std::cout << i.getValue<int>() << ", " << i.getType() << std::endl; std::cout << f.getValue<float>() << ", " << f.getType() << std::endl; std::cout << s.getValue<std::string>() << ", " << s.getType() << std::endl; }Lässt sich leicht erweitern und der Typ kann auch mit getType zur Laufzeit ermittelt werden. und mit getValue<Typ> abgefragt werden.
-
Oha, das kann ja was werden. Da werd ich mich dan mal am WE ran setzen. Danke dir für deine Mühe, jkljkl ( sehr kreativer nick ^^).

-
jkljkl ist der Bruder von asdasd

-
Ahnenforscher schrieb:
jkljkl ist der Bruder von asdasd

Ist janjan auch mit denen verwandt? :p