sách gpt4 ai đã đi

operator-overloading - C++11 重载 `M operator+(M&&,M&&)`

In lại 作者:行者123 更新时间:2023-12-04 08:21:10 25 4
mua khóa gpt4 Nike

làm mới:澄清、更明确的重点和缩短的示例:

  • 我可以避免 M op+(M&&,M&&) 过载吗?假设,我想很好地处理 RValues?我想其他三个重载Đúng必需的。

我首先使用 (&&,&&) 重载的原因:

  • 通常我不会提供M op+(&&,&&),但我似乎需要它:当为(&&,&)提供重载时(&,&&) 编译器陷入歧义。有没有比添加另一个实现变体更好的解决方法?

您还可以查看 complete代码。

struct Matrix {
...
// 2ary ops
friend Matrix operator+(const Matrix &a, Matrix &&b ) { b+=a; return move(b); }
friend Matrix operator+(Matrix &&a, const Matrix &b) { a+=b; return move(a); }
friend Matrix operator+(const Matrix &a, Matrix v) { v+=a; return v; }
friend Matrix operator+(Matrix &&a, Matrix &&b) { a+=b; return move(a); }
// ... same for operator*
// ... assume impl of operator+=,*= and move semantics
};

int chính() {
Matrix a{2},b{3},c{4},d{5};
Matrix x = a*b + c*d; // reuires &&,&& overload
std::cout << x << std::endl;
}

1 Câu trả lời

如果第一个值是右值,则以下辅助函数返回第一个值,否则返回第二个值(可能是右值,但也可能不是)。

template 
typename std::enable_if::value, T1&&>::type
get_rvalue(T1&& t1, T2&& t2) { return std::forward(t1); }

template
typename std::enable_if<>::value, T2&&>::type
get_rvalue(T1&& t1, T2&& t2) { return std::forward(t2); }

下面的辅助函数返回上面没有返回的其他值。

template 
typename std::enable_if::value, T1&&>::type
get_non_rvalue(T1&& t1, T2&& t2) { return std::forward(t2); }

template
typename std::enable_if<>::value, T2&&>::type
get_non_rvalue(T1&& t1, T2&& t2) { return std::forward(t1); }

这只是比较两种类型是否相同,忽略引用和常量。

template 
struct is_same_decay : public std::is_same<
typename std::decay::type,
typename std::decay::type
> {};

然后我们可以像下面这样(使用模板)为每个函数做一个重载:

// 2ary ops
template
friend typename std::enable_if<
is_same_decay::value &&
is_same_decay::value,
Matrix>::type
operator+(M1&& a, M2&& b)
{
Matrix x = get_rvalue(std::forward(a), std::forward(b));
x += get_non_rvalue(std::forward(a), std::forward(b));
return x;
}

template
friend typename std::enable_if<
is_same_decay::value &&
is_same_decay::value,
Matrix>::type
operator*(M1&& a, M2&& b)
{
Matrix x = get_rvalue(std::forward(a), std::forward(b));
x *= get_non_rvalue(std::forward(a), std::forward(b));
return x;
}

注意上面,如果 M1 hoặc M2 是一个右值,get_rvalue(a, b) 将返回一个右值,因此在这个case Matrix x 将由 move 而不是副本填充。命名返回值优化可能会确保不需要复制(甚至 move )到返回值中,因为 x 将在返回值的位置构造。

完整代码是 đây .

关于operator-overloading - C++11 重载 `M operator+(M&&,M&&)`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7173498/

25 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com