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/