LoginSignup
2
1

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-11-20

変な動的分岐をします
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

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1