【发布时间】:2018-07-20 06:20:35
【问题描述】:
我在整个项目中都使用boost-variant,我认为它是boost 中最有用和最通用的工具之一。
但如果涉及递归嵌套变体的访问者模式的复杂使用,调试有时会很麻烦。
因此我决定实现一个可重复使用的DebugVisitor,它可能会添加到我现有的访问者中。如果出现缺陷,它应该很容易添加/删除给我现有的访问者。
易于移除意味着它应该可以添加到任何现有的访问者类中,而不是修改使用访问者实例的地方。
我试图找到一个符合我要求的解决方案。以下代码编译,但不幸的是它没有打印消息。
有人知道为什么吗?
#include <iostream>
#include <boost/variant.hpp>
#include <functional>
template<typename V> // V must have the boost::static_visitor Interface
struct DebugVisitor : public V {
template<typename U>
typename V::result_type operator()(const U& u) const {
std::cout << "Visiting Type:" << typeid(U).name() << " with Visitor: " << typeid(V).name() << std::endl;
return V::operator()(u);
}
};
struct AddVisitor : public DebugVisitor<boost::static_visitor<boost::variant<int, double>>> {
template<typename U>
result_type operator()(const U& u) const {
return u + 1.;
}
};
int main(int, char**) {
boost::variant<double, int> number{ 3.2 };
AddVisitor d;
auto incr=number.apply_visitor(d);
if (auto dValue = boost::get<double>(incr)) {
std::cout << "Increment: " << dValue << std::endl;
}
return 0;
}
【问题讨论】:
-
你的第一个例子使用
T,但没有定义它 -
@Caleth:谢谢。我删除了旧解决方案。
标签: c++ crtp boost-variant visitor-pattern