I was working out a way to implement some type of generic object, something similar to boost::any. I don't have any boost sources laying around, so I'm not quite sure how they achieve it.
This is what I came up with so far:
Code:template <typename T> inline const char* TypeOf() { return typeid(T).name(); } template <typename T> inline const char* TypeOf(T obj) { return typeid(obj).name(); } class Object { void* ptr; const char* m_type; public: template <typename T> Object(T obj) { m_type = TypeOf(obj); ptr = new T(obj); } Object(Object& obj) { m_type = obj.m_type; ptr = obj.ptr; obj.ptr = 0; } ~Object() { if(ptr) delete ptr; } template <typename T> operator T() { return *((T*)ptr); } const char* Type() const { return m_type; } };Code:int main() { vector<Object> objects; objects.push_back(42); objects.push_back(88); objects.push_back(3.14159f); objects.push_back('c'); objects.push_back(string("Hello!")); objects.push_back(1337L); auto lambda = [](Object obj) { if(obj.Type() == TypeOf<int>()) { cout << static_cast<int>(obj) << "\n"; } else if(obj.Type() == TypeOf<float>()) { cout << static_cast<float>(obj) << "\n"; } else if(obj.Type() == TypeOf<char>()) { cout << static_cast<char>(obj) << "\n"; } else if(obj.Type() == TypeOf<string>()) { cout << static_cast<string>(obj) << "\n"; } else { cout << "Unknown type" << "\n"; } }; for_each(objects.begin(), objects.end(), lambda); system("PAUSE"); return 0; }




Reply With Quote