KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Consider the following: struct vec { int v[3]; vec() : v() {}; vec(int x, int y, int z) : v{x,y,z} {}; vec(const vec& that) = default; 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]); } vec&& operator+(vec&& lhs, const vec& rhs) { return move(lhs += rhs); } vec&& operator+(const vec& lhs, vec&& rhs) { return move(rhs += lhs); } vec&& operator+(vec&& lhs, vec&& rhs) { return move(lhs += rhs); } Thanks to r-value references, with these four overloads of operator+ I can minimize the number of objects created, by reusing temporaries. But I don't like the duplication of code this introduces. Can I achieve the same with less repetition?
Tags (comma-separated)
Save Edits
Cancel