c++ - 如何改变 boost::variant operator < 的行为

标签 c++ boost operator-overloading boost-variant

boost::variant 定义运算符 < 如下:

If which() == rhs.which() then: content_this < content_rhs, where content_this is the content of *this and content_rhs is the content of rhs. Otherwise: which() < rhs.which().

这不是我想要的,因为我想失败一些 < 比较。例如,如果我有这样的变体:

typedef boost::variant<int, double, std::string> DataType;

我希望 DataType(1) < DataType(2.0) 成功,但 DataType(1) < DataType("2") 抛出异常。有什么办法可以实现吗?

我无法定义

bool operator < (const Field& lhs, const Field& rhs)

因为它会和变体类中定义的成员运算符<发生冲突。

我可以定义一个 static_visitor,但我想知道是否有重载运算符 <.

最佳答案

虽然将您的DataType 包装在另一个结构中肯定是最好的解决方案,但请记住,如果您需要快速而肮脏的修复,此方法可行:

namespace boost
{
template<>
bool DataType::operator<(const DataType &) const
{   
    // impl
}
}

在 C++11 中,您应该能够避免命名空间 boost

请注意,除非您的所有 TU 在实际使用之前看到此特化,否则这将破坏 ODR。

关于c++ - 如何改变 boost::variant operator < 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28371824/

相关文章:

c++ - XCode导入C++工程问题: "referenced from"

c++ - 使用 boost 编译时出错

c++ - boost::noncopyable 的优点是什么

c++ - Boost with eclipse找不到线程库

operator-overloading - Rust 看不到我重载的 f64 乘法运算符

c++ - 你如何打印 std::regex?

c++ - 在 Windows 中获取用户临时文件夹路径

c++ - 一组自定义类对象及其 < 运算符

C++ 使用 vector 重载输出

c++ - 使用具有默认值的引用参数是好习惯吗?