c++return-valuereturn-type

Options for returning multiple types from a method


I want a method to alter multiple variables outside of it, which, if I understand correctly wouldn't/couldn't change outside the scope of that function, unless specifying and returning a specific type. I also know I can't return multiple types from a function.

struct multiTypes {
    int i = 0;
    float f = 1.0;

    std::string a = "testing";
};

multiTypes test() {
    multiTypes mT;
    mT.i += 2;

    return mT;
}

int main() {

    std::cout << test().i << '\n';
    std::cout << test().f << '\n';
    std::cout << test().a << '\n';
}

While this does work, I was wondering, what other alternatives exist to achieve the same result?


Solution

  • Yes, it's perfectly fine to define a type to hold multiple return values for a particular function.

    Take a look at std::in_in_out_result, it's basically the same as your type, and is used by a number of functions in the standard library.

    You should give the type and its members meaningful names, but there isn't any context as to what those would be from the minimal example in your question.

    What other alternatives exist to achieve the same result?

    If you do have meaningful names, this is preferable to having test return std::tuple<int, float, std::string>, which is another type that can hold those three values.

    std::tuple<int, float, std::string> acceptable_test() {
        return { 2, 1.0, "testing" };
    }
    

    Either of those is better than having test take reference parameters to those values, as it is not obvious from call sites that the values are all overwritten

    void bad_test(int& i, float& f, std::string& a) {
        i = 2;
        f = 1.0;
        a = "testing";
    }