提升::变体的默认访客功能
default visitor function for 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()
:
住在科里鲁
#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]
相关文章:
- 在访客模式中组合访客
- 隐藏重载虚拟功能的模板化访客:SFINAE 在使用?
- C++提升::获取和访客
- 如何消除访客模式冗余?
- 虚拟模板函数:使用参数实现访客模式
- 究竟发生了什么,我们需要在 c++ 中双重调度/访客
- 访客设计模式和多层类层次结构
- VirtualBox访客添加汇编
- 具有不同返回类型的变体访客
- 基类中的访客模式
- 提升::访客操作员过载的变体"Error: no match for call to [...]"
- 为什么在 BGL 中的访客中无法更改边缘属性?
- 非周期访客C++
- C++ 访客模式与子类节点上的访客失去"is a"关系
- 访客模式适用于shared_ptr或原始指针?
- 提升变体和访客
- Lambdas的多态性访客
- 工厂返回提升::访客对象
- 提升的访客模式::任何
- 提升::变体的默认访客功能