boost::any
boost::anyã¯åçåã¨ãè¨ããã¦ãã¾ããã¾ãã§åçåä»ãè¨èªã®ããã«boost::anyã«ã¯ããããåã®ãªãã¸ã§ã¯ããä»£å ¥ããåãåºããã¨ãã§ãã¾ããboost::anyã«æ ¼ç´ãããã¨ãåºæ¥ãåã®è¦ä»¶ã¯ä»¥ä¸ã®3ã¤ã§ãã
- ã³ãã¼ã³ã³ã¹ãã©ã¯ãå¯è½ãªãã¨
- ä¾å¤ã«å¯¾ãã¦å¼·ãä¿è¨¼ããã£ãä»£å ¥æ¼ç®åããããã¨
- ãã¹ãã©ã¯ã¿ãä¾å¤ãæããªãä¿è¨¼ããã¦ãããã¨
以ä¸ã®3ç¹ãæºãããåãªãboost::anyã«æ ¼ç´ãããã¨ãã§ãã¾ããã¨ãã£ã¦ãæ®éã¯ã©ããªã¯ã©ã¹ãä½ã£ã¦ããã¹ãã©ã¯ã¿ã¯ä¾å¤ãæããªãã«ããã®ã¯å½ããåã§ãããä»£å ¥å¯è½ãªã¯ã©ã¹ãªãä¾å¤ãæããªãswapãç¨ãã¦ã³ãã¼ã¨äº¤ææ³ã§ä»£å ¥æ¼ç®åãä¾å¤ã«å¯¾ãã¦å¼·ãä¿è¨¼ãããå®ç¾©ãããã®ã¯ãããããã¨ãªã®ã§ãå®è³ªã»ã¼ãã¹ã¦ã®åã§ä½¿ãã¾ããæ ¼ç´ãããªãã¸ã§ã¯ãã¯any_castã使ã£ã¦åãåºããã¨ãã§ãã¾ãããã£ã¹ãã«å¤±æããæã¯bad_any_castä¾å¤ãæãããã¾ãã
以ä¸ãµã³ãã«ã§ãã
#include <iostream> #include <string> #include <vector> #include <boost/any.hpp> int main() { std::vector<boost::any> vec; vec.push_back(3); vec.push_back(3.14f); vec.push_back(3.14159); vec.push_back(std::string("3.14")); for(const auto& it : vec) { if(it.type() == typeid(int)) { std::cout << "int " << boost::any_cast<int>(it) << std::endl; } else if(it.type() == typeid(float)) { std::cout << "float " << boost::any_cast<float>(it) << std::endl; } else if(it.type() == typeid(double)) { std::cout << "double " << boost::any_cast<double>(it) << std::endl; } else if(it.type() == typeid(std::string)) { std::cout << "std::string " << boost::any_cast<std::string>(it) << std::endl; } } }
å®è¡çµæ
int 3 float 3.14 double 3.14159 std::string 3.14 ç¶è¡ããã«ã¯ä½ããã¼ãæ¼ãã¦ãã ãã . . .
ãã®ããã«ãããããåãæ ¼ç´ãããã¨ãã§ããã³ã³ãããããããªã³ã³ããã¨è¨ãããã§ãã