我使用clang + libc++编写了 Fred Nurk 的答案。我不得不删除初始化器语法的使用,因为 clang 还没有实现它。我还在复制构造函数中放置了一条打印语句,以便我们可以计算副本。
#include <iostream>
template<class T>
struct AddPlus {
friend T operator+(T a, T const &b) {
a += b;
return a;
}
friend T&& operator+(T &&a, T const &b) {
a += b;
return std::move(a);
}
friend T&& operator+(T const &a, T &&b) {
b += a;
return std::move(b);
}
friend T&& operator+(T &&a, T &&b) {
a += b;
return std::move(a);
}
};
struct vec
: public AddPlus<vec>
{
int v[3];
vec() : v() {};
vec(int x, int y, int z)
{
v[0] = x;
v[1] = y;
v[2] = z;
};
vec(const vec& that)
{
std::cout << "Copying\n";
v[0] = that.v[0];
v[1] = that.v[1];
v[2] = that.v[2];
}
vec& operator=(const vec& that) = default;
~vec() = default;
vec& operator+=(const vec& that)
{
v[0] += that.v[0];
v[1] += that.v[1];
v[2] += that.v[2];
return *this;
}
};
int main()
{
vec v1(1, 2, 3), v2(1, 2, 3), v3(1, 2, 3), v4(1, 2, 3);
vec v5 = v1 + v2 + v3 + v4;
}
test.cpp:66:22: error: use of overloaded operator '+' is ambiguous (with operand types 'vec' and 'vec')
vec v5 = v1 + v2 + v3 + v4;
~~~~~~~ ^ ~~
test.cpp:5:12: note: candidate function
friend T operator+(T a, T const &b) {
^
test.cpp:10:14: note: candidate function
friend T&& operator+(T &&a, T const &b) {
^
1 error generated.
我像这样修复了这个错误:
template<class T>
struct AddPlus {
friend T operator+(const T& a, T const &b) {
T x(a);
x += b;
return x;
}
friend T&& operator+(T &&a, T const &b) {
a += b;
return std::move(a);
}
friend T&& operator+(T const &a, T &&b) {
b += a;
return std::move(b);
}
friend T&& operator+(T &&a, T &&b) {
a += b;
return std::move(a);
}
};
运行示例输出:
Copying
Copying
接下来我尝试了 C++03 方法:
#include <iostream>
struct vec
{
int v[3];
vec() : v() {};
vec(int x, int y, int z)
{
v[0] = x;
v[1] = y;
v[2] = z;
};
vec(const vec& that)
{
std::cout << "Copying\n";
v[0] = that.v[0];
v[1] = that.v[1];
v[2] = that.v[2];
}
vec& operator=(const vec& that) = default;
~vec() = default;
vec& operator+=(const vec& that)
{
v[0] += that.v[0];
v[1] += that.v[1];
v[2] += that.v[2];
return *this;
}
};
vec operator+(const vec& lhs, const vec& rhs)
{
return vec(lhs.v[0] + rhs.v[0], lhs.v[1] + rhs.v[1], lhs.v[2] + rhs.v[2]);
}
int main()
{
vec v1(1, 2, 3), v2(1, 2, 3), v3(1, 2, 3), v4(1, 2, 3);
vec v5 = v1 + v2 + v3 + v4;
}
运行这个程序根本没有产生任何输出。
这些是我使用clang++得到的结果。用你可能的方式解释它们。你的里程可能会有所不同。