C++
boost

boost::variantでポリモーフィズムっぽい変なことをする

More than 3 years have passed since last update.

変な動的分岐をします

visitorでtemplateを使うことがポイントです

#include <iostream>

#include <string>
#include <boost/variant.hpp>

class TypeA {
public:
std::string toString() const {
return "TypeA";
}
};

class TypeB {
public:
std::string toString() const {
return "TypeB";
}
};

class VariantType {
public:
template <class T>
VariantType &operator=(const T &value) {
_value = value;
return *this;
}

struct ToStringVisitor : public boost::static_visitor<std::string> {
template <class T>
std::string operator()(const T &arg) const {
return arg.toString();
}
};
std::string toString() const {
return boost::apply_visitor(ToStringVisitor(), _value);
}

private:
boost::variant<TypeA, TypeB> _value;
};

int main(int argc, const char *argv[]) {
VariantType v1;
VariantType v2;

v1 = TypeA();
v2 = TypeB();

std::cout << v1.toString() << std::endl;
std::cout << v2.toString() << std::endl;

return 0;
}

出力:

TypeA

TypeB