Function that accepts both lvalue and rvalue arguments

后端 未结 6 1080
长发绾君心
长发绾君心 2020-12-08 13:13

Is there a way to write a function in C++ that accepts both lvalue and rvalue arguments, without making it a template?

For example, suppose I write a function

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 14:09

    There is not much of a sane choice other than offering two overloads or making your function a template, I would say.

    If you really, really need an (ugly) alternative, then I guess the only (insane) thing you can do is to have your function accept a const&, with a pre-condition saying that you cannot pass an object of a const-qualified type to it (you don't want to support that anyway). The function would then be allowed to cast away the constness of the reference.

    But I'd personally write two overloads and define one in terms of the other, so you do duplicate the declaration, but not the definition:

    void foo(X& x) 
    { 
        // Here goes the stuff... 
    }
    
    void foo(X&& x) { foo(x); }
    

提交回复
热议问题