Returning multiple values from a C++ function

后端 未结 21 2772
别跟我提以往
别跟我提以往 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:38

    Use a struct or a class for the return value. Using std::pair may work for now, but

    1. it's inflexible if you decide later you want more info returned;
    2. it's not very clear from the function's declaration in the header what is being returned and in what order.

    Returning a structure with self-documenting member variable names will likely be less bug-prone for anyone using your function. Putting my coworker hat on for a moment, your divide_result structure is easy for me, a potential user of your function, to immediately understand after 2 seconds. Messing around with ouput parameters or mysterious pairs and tuples would take more time to read through and may be used incorrectly. And most likely even after using the function a few times I still won't remember the correct order of the arguments.

提交回复
热议问题