c++ - operator<< with boost::variant 是如何实现的

标签 c++ templates boost c++14 boost-variant

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

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

我们如何制作 operator<<对于像这样的结构,打印缓冲区中存储的类型并将其传递给 operator<<对于 cout ?为此,我们需要知道存储在缓冲区中的元素的类型,对吧?有没有办法知道这一点?

此外,我正在寻找对此类实现的解释(如果存在的话)。不仅仅是它的存在以及我如何使用它。

最佳答案

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

与:

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

您可以在 tutorial 中看到一些其他示例.

关于c++ - operator<< with boost::variant 是如何实现的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36223247/

相关文章:

初始化可以使用其名称的 C++ 数据结构

c++ - g++ std::is_function 实现:_ArgTypes 后跟 6 个句点是什么意思?

C++11 性能 : Lambda inlining vs Function template specialization

html - CSS 样式表未显示在着陆页上

c++ - '.' 标记前缺少模板参数

c++ - boost 几何交集给出奇怪的结果

c++ - 在已打开的文件上删除ItemAtPath

c++ - 构造函数中的数组设置意味着稍后失败

c++ - 一般来说,boost bind 在幕后是如何工作的?

c++ - 如何从 boost::python::list 中提取值到 C++