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/