提升::变体的默认访客功能

default visitor function for boost::variant

本文关键字:访客 功能 默认 提升      更新时间:2023-10-16

假设我有这样一个变体定义:

typedef boost::variant <
v1,
v2,
v3,
...
vn
> v;

我需要为每个 v1 到 vn 编写一个带有访客函数的访问者类,如下所示:

class myvisitor : public boost::static_visitor<bool> {
  bool operator()(v1) {}
  bool operator()(v2) {}
   ...
  bool operator()(vn) {}
}

因此,如果除了 v1 的函数之外,所有这些函数都相同,那么我只想定义

 bool operator()(v1) {}

同时将所有其他形式保留为某种默认形式,以避免编写大量无用和重复的代码。

那么如果这是可能的呢?或者Boost开发人员可以在他的下一个版本中做到这一点吗?

只需将默认的"case"设为打开的模板成员operator()

住在科里鲁

#include <boost/variant.hpp>
#include <iostream>
struct MyStruct {
    int a, b, c;
};
using V = boost::variant<int, MyStruct, std::string, double>;
struct MyVisitor : boost::static_visitor<void> {
    void operator()(int) const                 { std::cout << __PRETTY_FUNCTION__ << "n"; } 
    void operator()(std::string const &) const { std::cout << __PRETTY_FUNCTION__ << "n"; } 
    // the default case:
    template <typename T> void operator()(T const &) const {
        std::cout << "FALLBACK: " << __PRETTY_FUNCTION__ << "n"; 
    } 
};
int main() {
    V v;
    for (auto v : { V(42), V(3.14), V("hello world"), V( MyStruct{1,2,3} ) })
        boost::apply_visitor(MyVisitor(), v);
}

输出:

void MyVisitor::operator()(int) const
FALLBACK: void MyVisitor::operator()(const T&) const [with T = double]
void MyVisitor::operator()(const string&) const
FALLBACK: void MyVisitor::operator()(const T&) const [with T = MyStruct]