Returning multiple values from a C++ function

后端 未结 21 2765
别跟我提以往
别跟我提以往 2020-11-22 01:04

Is there a preferred way to return multiple values from a C++ function? For example, imagine a function that divides two integers and returns both the quotient and the rema

21条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 01:54

    With C++17 you can also return one ore more unmovable/uncopyable values (in certain cases). The possibility to return unmovable types come via the new guaranteed return value optimization, and it composes nicely with aggregates, and what can be called templated constructors.

    template
    struct many {
      T1 a;
      T2 b;
      T3 c;
    };
    
    // guide:
    template
    many(T1, T2, T3) -> many;
    
    auto f(){ return many{string(),5.7, unmovable()}; }; 
    
    int main(){
       // in place construct x,y,z with a string, 5.7 and unmovable.
       auto [x,y,z] = f();
    }
    

    The pretty thing about this is that it is guaranteed to not cause any copying or moving. You can make the example many struct variadic too. More details:

    Returning variadic aggregates (struct) and syntax for C++17 variadic template 'construction deduction guide'

提交回复
热议问题