[英]Comparing a boost::optional<T&> to const T&
I'm trying to compare a constant reference and a non-constant optional object with the same type. 我正在尝试比较具有相同类型的常量引用和非常量可选对象。 I have a type,
NonCopy
, which is noncopyable 我有一个
NonCopy
类型,它是NonCopy
#include <iostream>
#include <boost/optional.hpp>
struct NonCopy {
NonCopy() { }
NonCopy(const NonCopy&) = delete;
NonCopy& operator=(const NonCopy&) = delete;
};
int main()
{
NonCopy nc;
const NonCopy& object = nc;
boost::optional<NonCopy&> object2 = nc;
if (!object2 && object2.get() != object) {
std::cout << "not equal?\n";
}
}
Which yields 哪个产量
error: no match for ‘operator!=’ (operand types are ‘boost::optional_detail::types_when_is_ref<NonCopy&>::raw_type {aka NonCopy}’ and ‘const NonCopy’)
I've tried multiple variations on the theme, including 我已经尝试过多种主题,包括
if (object2 && const_cast<const NonCopy&>(object2.get()) != object)
Which yields a very interesting error of 产生一个非常有趣的错误
error: no match for ‘operator!=’ (operand types are ‘const NonCopy’ and ‘const NonCopy’)
and lists candidates for != on boost::optional<NonCopy>
(such as bool boost::operator!=(const boost::optional<NonCopy>&, const boost::optional<NonCopy>&)
), rather than on NonCopy
. 并在
boost::optional<NonCopy>
上列出!=的候选对象(例如bool boost::operator!=(const boost::optional<NonCopy>&, const boost::optional<NonCopy>&)
),而不是在NonCopy
。
Since object2.get()
returns a NonCopy&
, your example effectively simplifies to: 由于
object2.get()
返回NonCopy&
,因此您的示例有效地简化为:
NonCopy nc;
const NonCopy& object = nc;
NonCopy& object2 = nc;
object != object2; // error: no match for operator!=
That simply means that your type NonCopy
has no operator!=
. 这只是意味着您的类型
NonCopy
没有operator!=
。 Implement that, and your code will compile. 实现这一点,您的代码将被编译。
boost::optional
is not relevant here. boost::optional
在这里不相关。
Although note that you're checking: 尽管注意您正在检查:
if (!object2 && object2.get() != object)
^^^^^^^^ ^^^^^^^^^^^^^
object2 is none, but get it anyway?
That is undefined behavior. 那是未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.