简体   繁体   English

如何实现operator << with boost :: variant

[英]How operator<< with boost::variant is implemented

I understand that boost::variant is implemented something like so 据我所知, boost::variant实现了类似的东西

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

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 ? 我们如何为这样的结构创建一个operator<< ,它打印存储在缓冲区中的类型转换并将其传递给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 has an apply_visitor function, that takes a generic function object and passes the type of the variant into it. Boost有一个apply_visitor函数,它接受一个泛型函数对象并将变量的类型传递给它。 So implementing operator<< is as straightforward as: 所以实现operator<<就像以下一样简单:

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

with: 有:

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

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

Or simply: 或者干脆:

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);
}

You can see some other examples in the tutorial . 您可以在本教程中看到其他一些示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM