我在整个项目中都使用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;
}发布于 2018-07-27 08:13:31
您看不到调试输出的原因是因为AddVisitor::operator()没有调用DebugVisitor::operator()。如果是这样的话,您将遇到一个错误,试图解决不存在的boost::static_visitor<>::operator()。
备选案文1。
只是在AddVisitor定义中有条件地编译调试
struct AddVisitor : public boost::static_visitor<boost::variant<int, double>> {
template<typename U>
result_type operator()(const U& u) const {
#ifdef DEBUG
std::cout << "Visiting Type:" << typeid(U).name() << " with Visitor: " << typeid(AddVisitor).name() << std::endl;
#endif
return u + 1.;
}
};备选案文2。
有条件地定义要由AddVisitor包装的符号DebugVisitor
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 AddVisitorBase : public boost::static_visitor<boost::variant<int, double>> {
template<typename U>
result_type operator()(const U& u) const {
return u + 1.;
}
};
#ifdef DEBUG
using AddVisitor = DebugVisitor<AddVisitorBase>;
#else
using AddVisitor = AddVisitorBase;
#endif备选方案3。
一对CRTP碱基
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::call(u);
}
};
template<typename V> // V must have the boost::static_visitor Interface
struct NotDebugVisitor : public V {
template<typename U>
typename V::result_type operator()(const U& u) const {
return V::call(u);
}
};
struct AddVisitor : public boost::static_visitor<boost::variant<int, double>>, public
#ifdef DEBUG
DebugVisitor<AddVisitor>
#else
NotDebugVisitor<AddVisitor>
#endif
{
template<typename U>
result_type call(const U& u) const {
return u + 1.;
}
};https://stackoverflow.com/questions/51436206
复制相似问题