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

Cur*_*ous 4 c++ templates boost boost-variant c++14

我明白这boost::variant是实现的

template <typename... Vs>
struct variant {
    std::aligned_union<Vs...>::type buffer;
    ....
};
Run Code Online (Sandbox Code Playgroud)

我们如何operator<<为这样的结构创建一个这样的结构来打印存储在缓冲区中的类型转换并将其传递operator<<cout?为此,我们需要知道缓冲区中存储的元素的类型吗?有没有办法知道这个?

此外,我正在寻找这种实现的解释,如果存在的话.不只是它存在以及如何使用它.

Bar*_*rry 5

Boost有一个apply_visitor函数,它接受一个泛型函数对象并将变量的类型传递给它.因此,实施operator<<与以下一样简单:

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

有:

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

    template <class T>
    std::ostream& operator()(T const& val) {
        return os << val;
    }
};
Run Code Online (Sandbox Code Playgroud)

或者干脆:

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);
}
Run Code Online (Sandbox Code Playgroud)

您可以在本教程中看到其他一些示例.

  • @Curious我真的不会在评论中解释"变种如何运作".您可以查看boost实现,有很多关于如何在C++中实现变体类型的博客文章. (4认同)