c++ - 使输出流运算符为 boost::variant<std::vector<int>, int, double> 工作的正确方法是什么

标签 c++ c++11 boost boost-variant

boost::variant为自己实现一个流操作符。 问题是 std::vector<> 没有-- 但是 boost::variant假设传递给 boost::variant 的每一种类型都有一个实现.那么在哪里实现这个操作符呢?最好在某个 namespace 中,它不会与其他人的实现发生冲突。 据我了解,可以实现

template<typename T>
std::ostream &operator<<(std::ostream&, const std::vector<T>&);

std命名空间或 std::vector 的流式运算符所在的命名空间中正在从 -- 在本例中调用 boost::detail::variant

我都不喜欢。还有其他办法吗?

最佳答案

在命名空间中添加内容 std未定义的B行为。

在外部命名空间中添加内容并不好,即使是合法的。但无论如何它都无法解决您的 ADL 问题( template <typename T> std::ostream &operator<<(std::ostream&, const std::vector<T>&); 仅将 std 用于 ADL(以及 T 的命名空间))

脆弱的修复方法是将它放在全局命名空间中,但是你必须在 boost 之前包含它 operator <<定义:-/

作为替代方案,您可以使用常规方式来处理 variant并使用访问者:

struct Printer
{
    template <typename T>
    void operator() (const T& e) const { std::cout << e; }

    template <typename T>
    void operator() (const std::vector<T>& v) const
    {
        // Your implementation, such as
        for (const auto& e : v) {
            std::cout << e << std::endl;
        }
    }

};


boost::visit(Printer{}, my_variant);

关于c++ - 使输出流运算符为 boost::variant<std::vector<int>, int, double> 工作的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51714602/

相关文章:

c++ - constexpr exp、log、pow

python - Boost.Python - 如何通过引用返回?

c++ - 绑定(bind)运算符新?

c++ - 将指针传递给函数

c++ - 带有 const 的外部 "C"

c++寻找一种干净有效的方法来获取子矩阵

c++ - 在 C++ 中传递 'implied' (?) 引用时是否生成拷贝

c++ - lambda 函数的静态数组 (C++)

C++ mmap到 "fast"读取与gzip文件的耦合

C++ Windows JPEG 到字节流