c++ - boost::variant 的默认访问者函数

标签 c++ boost boost-variant

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

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():

Live On Coliru

#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]

关于c++ - boost::variant 的默认访问者函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34763219/

相关文章:

c++ - 如何简化 make_variant_over 生成的类型

c++ - g++ -fno-enforce-eh-specs - 为什么/如何违反 C++ 标准?

c++ - boost 正则表达式子字符串匹配

c++ - 模板构造函数中的模板类特化

c++ - 标准 vector 和 boost 数组 : which is faster?

c++ - Boost 1.46.1,属性树 : How to iterate through ptree receiving sub ptrees?

c++ - Boost::spirit 流程规则与分支不正确

c++ - 将 QStringList 元素拆分为更多元素

c++ - 实现运算符重载的最佳方式是什么?

c++ - QWidget keyPressEvent 覆盖