【发布时间】:2020-04-02 15:08:11
【问题描述】:
假设我们有 Base 类及其成员函数 Base doSomething(const Base& other)。 我想知道如何确定这个或其他对象是否是右值, 例如我需要类似的东西
Base Base::doSomething(const Base& other) {
...
if(this_is_rvalue) {
// use resources of *this
}
else if(other_is_rvalue) {
// use resources of other
}
...
}
我知道可能的解决方案是使用模板化朋友功能:
template<typename T1, typename T2, typename = typename std::enable_if<.....>::type>
friend Base doSomething(T1&& this_, T2&& other) {
...
if(std::is_rvalue_reference<T1&&>::value) {
// use resources of this_
return std::move(this_);
}
else if(std::is_rvalue_reference<T2&&>::value) {
// use resources of other
return std::move(other);
}
}
但是在我的情况下这种方法是非常不可取的
提前致谢!
【问题讨论】:
-
抱歉,忘记添加 const,已更正
-
那么
other再次不是右值,而是可能绑定或不绑定到右值的左值。但同样,编译器会保护你,重用资源需要对 const 引用进行非 const 访问,所以这是不可能的。 (当 const 引用指向非 const 对象时,请不要向const_cast提议,因为这确实是允许的,但只是邪恶的)
标签: c++ move-semantics rvalue-reference perfect-forwarding