std::variant
C++17ã«ã¯std::variantã¨ããã©ã¤ãã©ãªã追å ããã¾ãã variantã¯çµã¿è¾¼ã¿ã®unionãããªãããªã¤ã³ã¿ã¼ãã§ã¤ã¹ãæã£ãåå®å ¨ãªunionã§ãã*1 Visual Studio 2017ã«ãå ¥ãã¾ããã®ã§ç°¡åãªãµã³ãã«ãæ¸ãã¦ã¿ã¾ãã
#include <variant> #include <iostream> #include <string> struct visitor { void operator()(int) const { std::cout << "it's int" << std::endl; } void operator()(std::string const&) const { std::cout << "it's string" << std::endl; } }; int main() { std::variant<int, std::string> const vars[] = {3, "hello"}; for (auto const& it : vars) { // visitã§variantã®å¤ã«ã¢ã¯ã»ã¹ã§ãããå¤ããã¡ã³ã¯ã¿ã«æ¸¡ããã¨ãåºæ¥ãªãå ´åã¯ã³ã³ãã¤ã«ã¨ã©ã¼ã«ãªã // (å¿ è¦ãªãã°)ãã¡ã³ã¯ã¿ã¯ã¸ã§ããªã¯ã¹ã«ããããªã¼ãã¼ãã¼ããã¦ãã std::visit(visitor{}, it); // holds_alternativeã¯variantã«holds_alternativeã®ãã³ãã¬ã¼ãå¼æ°ã«æ¸¡ããåã®å¤ãæã£ã¦ããã°trueãè¿ã // variantã®ãã³ãã¬ã¼ãå¼æ°ã«åå¨ããªãåãæå®ããã¨ã³ã³ãã¤ã«ã¨ã©ã¼ã«ãªã std::cout << std::boolalpha << std::holds_alternative<int>(it) << std::endl; // std::getã§variantãä¿æãã¦ããå¤ã®åç §ãåå¾ãã // ãã³ãã¬ã¼ãå¼æ°ã«æ¸¡ããåã®å¤ãä¿æãã¦ããªãå ´åã¯std::bad_variant_accessãæãã try { int value = std::get<int>(it); std::cout << "holding int value: " << value << std::endl; } catch (std::bad_variant_access const& e) { std::cout << e.what() << std::endl; } // std::get_ifã§variantãä¿æãã¦ããå¤ã®ãã¤ã³ã¿ãåå¾ãã // ãã³ãã¬ã¼ãå¼æ°ã«æ¸¡ããæ¹ã®ããããä¿æãã¦ããªãå ´åã¯nullptrãè¿ã if (auto const value = std::get_if<int>(&it)) { std::cout << "holding int value: " << *value << std::endl; } else { std::cout << "not found" << std::endl; } } }
å®è¡çµæ
it's int true holding int value: 3 holding int value: 3 it's string false bad variant access not found Press any key to continue . . .
*1:代æ°ãã¼ã¿åç´ äººãªã®ã§éã£ã¦ãããåªããææãã¦ãã ããâ¦