您没有看到调试输出的原因是
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。
有条件地定义符号
添加访问者
被包裹着
DebugVisitor
template<typename V>
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>
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>
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.;
}
};