作为个人练习,我想使用 shared_ptr 实现访问者模式。我熟悉 Robert Martin 的非循环访问者论文,但发现虚拟 accept() 的侵入性以及为每个 {X} 类创建 {X}Visitor 类的必要性令人不快。我喜欢 boost::static_visitor 类,因为它在本地封装了所有逻辑,而无需 {X}::accept() 和 {X}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;
}