如何操作符<与boost :: variant实现 [英] How operator<< with boost::variant is implemented

查看:250
本文介绍了如何操作符<与boost :: variant实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 boost :: variant 实现的像这样

template <typename... Vs>
struct variant {
    std::aligned_union<Vs...>::type buffer;
    ....
};

我们如何使运算符<< 为这样的结构打印转换存储在缓冲区中的类型,并将其传递给运算符< c>?为此,我们需要知道存储在缓冲区中的元素的类型吗?是否有办法知道这个?

How can we make an operator<< for a struct like this that prints the casts the type stored in the buffer and passes that to operator<< for cout? For this we would need to know the type of the element stored in the buffer right? Is there a way to know this?

同时我正在寻找这样一个实现的解释,如果一个存在。不只是它存在,我如何使用它。

Also I am looking for an explanation of such an implementation, if one exists. Not just that it exists and how I can use it.

推荐答案

Boost有 apply_visitor 函数,它接受一个通用函数对象和将变体的类型传递给它。因此,实现运算符<< 非常简单:

Boost has an apply_visitor function, that takes a generic function object and passes the type of the variant into it. So implementing operator<< is as straightforward as:

template <class... Ts>
std::ostream& operator<<(std::ostream& os, boost::variant<Ts...> const& var) {
    return boost::apply_visitor(ostream_visitor{os}, var);
}

与:

struct ostream_visitor : boost::static_visitor<std::ostream&>
{
    std::ostream& os;

    template <class T>
    std::ostream& operator()(T const& val) {
        return os << val;
    }
};

或者:

template <class... Ts>
std::ostream& operator<<(std::ostream& os, boost::variant<Ts...> const& var) {
    return boost::apply_visitor([&os](const auto& val) -> std::ostream& {
        return os << val;
    }, var);
}

您可以在教程

这篇关于如何操作符&lt;与boost :: variant实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆