boost variant´Â ÅÛÇø´ ÆĶó¹ÌÅÍ·Î ÁöÁ¤µÈ µ¥ÀÌÅÍ Å¸ÀÔÀ» µ¥ÀÌÅÍ·Î °¡Áú¼ö Àִ Ŭ·¡½ºÀÌ´Ù. ¾÷±×·¹ÀÌµå µÈ unionÀ¸·Î ÈüÀ» »ç¿ëÇÏÁö ¾Ê°í RTTIµµ »ç¿ëÇÏÁö ¾Ê¾Æ¼ ¼º´Éµµ ÁÁ´Ù. variant ±âº» »ç¿ë¹ý #include <iostream>
#include <string> #include <boost/variant.hpp> struct Dog { std::string name; int age; }; struct PrintVisitor : boost::static_visitor<void> { void operator()(int x) const { std::cout << x << std::endl; } void operator()(std::string& s) const { std::cout << s << std::endl; } void operator()(Dog d) const { std::cout << d.name << ":" << d.age << std::endl; } }; int main() { boost::variant<int, std::string, Dog> v; Dog dog = {"molly", 3}; v = dog; //Variant Visitor boost::apply_visitor(PrintVisitor(), v); //ŸÀÔ À妽º std::cout << v.which() << std::endl; //ŸÀÔ Ã¼Å© if (v.type() == typeid(Dog)) { std::cout << "Dog" << std::endl; } //ÂüÁ¶ try { Dog& x = boost::get<Dog>(v); std::cout << x.age << std::endl; } catch (boost::bad_get& e) { std::cout << e.what() << std::endl; } //Æ÷ÀÎÅÍ : try~catch ´ë½Å null·Î üũ ÇÑ´Ù. if (int* x = boost::get<int>(&v)) std::cout << *x << std::endl; else std::cout << "int* is null" << std::endl; if (Dog* x = boost::get<Dog>(&v)) std::cout << x->name << std::endl; } »ó¼Ó´ë½Å variant »ç¿ëÇϱâ #include <iostream>
#include <vector> #include <string> #include <boost/variant.hpp> struct Actor { void Update() { std::cout << "Actor Update" << std::endl; } }; struct Npc { void Update() { std::cout << "Npc Update" << std::endl; } }; struct Effect { void Update() { std::cout << "Effect Update" << std::endl; } }; struct UpdateVisitor { using result_type = void; template <class T> void operator()(T& x) { x.Update(); } }; class ObjectList { using ObjectType = boost::variant<Actor, Npc, Effect>; std::vector<ObjectType> mList; public: void Update() { for (ObjectType& x : mList) { UpdateVisitor vis; boost::apply_visitor(vis, x); } } template <class Task, class... Args> void Add(Args... args) { mList.push_back(Task(args...)); } }; int main() { ObjectList objList; objList.Add<Actor>(); objList.Add<Npc>(); objList.Add<Effect>(); objList.Update(); return 0; } ÂüÁ¶) https://github.com/jacking75/CookBookBoostCpp/blob/master/variant.md http://zepeh.tistory.com/266 |