Boost.VariantにはNever Empty保証という考え方があり、一度値を入れてしまうと、他の値を入れることはできてもクリアすることはできません。
#include <iostream> #include <string> #include <boost/variant.hpp> int main() { boost::variant<int, std::string, double> v; // デフォルトコンストラクトはできる v = 3; // v.clear(); // そんな関数はない }
どうしてもクリアしたい場合は、boost::blankという型をvariantに格納できるように指定します。
これは単なる中身が空のクラスです。あとは、variant::which()やvariant::type()を使用して空かどうかを判定します。
#include <iostream> #include <string> #include <boost/variant.hpp> int main() { boost::variant<boost::blank, int, std::string> v = boost::blank(); v = 3; v = boost::blank(); if (v.type() == typeid(boost::blank)) { std::cout << "blank" << std::endl; } else { std::cout << "no blank" << std::endl; } }
blank