How to reduce redundant code when adding new c++0x rvalue reference operator overloads

后端 未结 4 1504
不思量自难忘°
不思量自难忘° 2020-12-08 05:29

I am adding new operator overloads to take advantage of c++0x rvalue references, and I feel like I\'m producing a lot of redundant code.

I have a class, tree

4条回答
  •  萌比男神i
    2020-12-08 05:40

    I think the problem is that you have defined the operation with non const parameters. If you define

    tree operator +(const tree& a, const tree& b);
    

    There is no difference between r-value and l-value reference, so you don't need to define also

    tree operator +(tree&&      a, const tree& b);
    

    If in addition double is convertible to tree as tree x = 1.23; lets think, you don't need neither define

    tree operator +(double      a, const tree& b){ return tree(a) + b; }
    

    the compiler will do the work for you.

    You will need to make the difference between rvalues and lvalues if the operator+ takes the tree parameter by value

    tree operator +(tree a, tree b);
    

提交回复
热议问题