Is it possible to take a parameter by const reference, while banning conversions so that temporaries aren't passed instead?

后端 未结 6 1448
面向向阳花
面向向阳花 2021-01-18 21:58

Sometimes we like to take a large parameter by reference, and also to make the reference const if possible to advertize that it is an input parameter. But by making the refe

6条回答
  •  醉梦人生
    2021-01-18 22:37

    If you can use C++11 (or parts thereof), this is easy:

    void f(BigObject const& bo){
      // ...
    }
    
    void f(BigObject&&) = delete; // or just undefined
    

    Live example on Ideone.

    This will work, because binding to an rvalue ref is preferred over binding to a reference-to-const for a temporary object.

    You can also exploit the fact that only a single user-defined conversion is allowed in an implicit conversion sequence:

    struct BigObjWrapper{
      BigObjWrapper(BigObject const& o)
        : object(o) {}
    
      BigObject const& object;
    };
    
    void f(BigObjWrapper wrap){
      BigObject const& bo = wrap.object;
      // ...
    }
    

    Live example on Ideone.

提交回复
热议问题