個人的な演習として、shared_ptrを使用してビジターパターンを実装したいと思います。私はRobertMartinの非巡回ビジターペーパーに精通していますが、仮想accept()の煩わしい性質と、{X}クラスごとに{X}Visitorクラスを作成する必要があるのは不快です。{X} :: accept()と{X} Visitorを必要とせずにすべてのロジックをローカルにカプセル化するので、boost::static_visitorクラスが好きです。
私が探しているのは、以下で説明するテンプレート関数関数ripを作成する方法のヒントです(私が言ったように、これは演習として行っています)。私はそれが次の形式でなければならないと思います:
template <typename U, typename T1, typename T2, ...>
boost::variant<T1, T2, ...> rip(U& p, boost::static_visitor<T1, T2, ...> sv)
{
if (T1 t1 = dynamic_cast<T1>(p)) return boost::variant<T1, ...>(t1);
... and so on, splitting static_visitor
return 0; // or throw an exception
}
同様のことを行うチュートリアルへのヒントやポインタをいただければ幸いです。ありがとう。
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <boost/bind.hpp>
#include <boost/variant.hpp>
struct Base {};
struct A : Base {};
struct B : Base {};
struct C : Base {};
typedef std::shared_ptr<Base> base_ptr;
typedef boost::variant<A*,B*,C*> base_variant;
struct variant_visitor : public boost::static_visitor<void> {
void operator()(A*, base_ptr) const {std::cout << "A*\n";}
void operator()(B*, base_ptr) const {std::cout << "B*\n";}
void operator()(C*, base_ptr) const {std::cout << "C*\n";}
};
int main(int, char**)
{
// This works, of course.
base_ptr b(new A());
base_variant v(new A());
boost::apply_visitor(boost::bind(variant_visitor(), _1, b), v);
// How could we use a shared_ptr with a variant? I almost see
// the template magic, a function to iterate over the template
// types from the variant_visitor and return an "any<...>".
// base_variant rip(base_ptr&, variant_visitor) {...}
// boost::apply_visitor(boost::bind(variant_visitor(), _1, b), rip(b, variant_visitor()));
return EXIT_SUCCESS;
}