c++0x の右辺値参照を利用するために新しい演算子のオーバーロードを追加していますが、多くの冗長なコードを生成しているように感じます。
tree
double 値に対する代数演算のツリーを保持するクラス があります。使用例を次に示します。
tree x = 1.23;
tree y = 8.19;
tree z = (x + y)/67.31 - 3.15*y;
...
std::cout << z; // prints "(1.23 + 8.19)/67.31 - 3.15*8.19"
各二項演算 (plus など) では、各辺は lvalue tree
、 rvalue tree
、またはのいずれかになりますdouble
。これにより、2 項演算ごとに 8 つのオーバーロードが発生します。
// core rvalue overloads for plus:
tree operator +(const tree& a, const tree& b);
tree operator +(const tree& a, tree&& b);
tree operator +(tree&& a, const tree& b);
tree operator +(tree&& a, tree&& b);
// cast and forward cases:
tree operator +(const tree& a, double b) { return a + tree(b); }
tree operator +(double a, const tree& b) { return tree(a) + b; }
tree operator +(tree&& a, double b) { return std::move(a) + tree(b); }
tree operator +(double a, tree&& b) { return tree(a) + std::move(b); }
// 8 more overloads for minus
// 8 more overloads for multiply
// 8 more overloads for divide
// etc
また、バイナリ演算 (マイナス、乗算、除算など) ごとに繰り返す必要があります。
ご覧のとおり、実際に記述する必要がある関数は 4 つだけです。他の 4 つはキャストしてコア ケースに転送できます。
このコードのサイズを小さくするための提案はありますか?
PS:このクラスは実際には単なる double のツリーよりも複雑です。コピーを減らすと、プロジェクトのパフォーマンスが劇的に向上します。したがって、余分なコードがあっても、右辺値のオーバーロードは私にとって価値があります。上記の「キャストアンドフォワード」のケースをテンプレート化する方法があるのではないかと疑っていますが、何も考えられないようです。