Function that accepts both lvalue and rvalue arguments

后端 未结 6 1088
长发绾君心
长发绾君心 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:02

    Be bold, embrace generic forward functions and name them well.

    template
    auto stream_meh_to(Stream&& s) 
    ->decltype(std::forward(s) << std::string{/*   */}){
        return std::forward(s) << std::string{"meh\n"};}
    

    Note that this will work with anything that will make sense for it to work, not only ostreams. That is a good thing.

    If the function is called with an argument that doesn't make sense, it will simply ignore this definition. Incidentally, this works better if indentation is set to 4 spaces. :)


    This is the same as Cube's answer, except that I am saying that it is, when possible, more elegant to not check for specific types and let generic programming do its thing.

提交回复
热议问题