【问题标题】:Is there boost::visit like std::visit, for boost::variant?对于 boost::variant,是否有类似 std::visit 的 boost::visit?
【发布时间】:2026-01-14 07:45:02
【问题描述】:

对于 C++14,我使用 boost::variant 作为编译时多态性的一种方式:

using MyType = boost::variant<A, B>;

两个类都有一个方法sayHello()。我想打电话:

MyType obj = ...; // either A() or B()
boost::visit([](auto&& o) { o.sayHello();}, obj);

我知道static_visitor 方式,但我觉得它很麻烦。有没有像std::visit 这样的boost::visit 我失踪了?如果没有,为什么不存在?

最小的例子here

【问题讨论】:

  • 您是否尝试过在 apply_visitor 中使用 lambda 而不是静态访问者? IRC,它应该“正常工作”(tm)。

标签: c++ boost c++14 boost-variant std-variant


【解决方案1】:

有,但它叫boost::apply_visitor。它与boost::variant 相关的行为是std::visitstd::variant

【讨论】: