Search code examples
c++functionreturn-typemultiple-return-values

Can a function return multiple values of varying types?


It thought it would be interesting to return multiple values (with different types!) from a C++ function call.

So I've looked around to maybe found some example code but unfortunately I could not find anything matching to this topic.

I'd like a function like ...

int myCoolFunction(int myParam1) {
    return 93923;
}

to work on different types to return multiple different types of values like

?whatever? myCoolFunction(int myParam1) {
    return { 5, "nice weather", 5.5, myCoolMat }
}

So is something like this possible using C++ (My idea was to use a special AnyType-vector but I could not find example code therefore) or do I have to stay on these type of call? (see below)

void myCoolFunction(cv::Mat &myMat, string &str){
   // change myMat
   // change str
}

Note: So the order and the count of the returned element will be the same every time - > The set stays identical (like 1.:double, 2.:int in every case)


Solution

  • If you want to return multiple values, you can return an instance of a class wrapping the different values.

    If you do not care about losing semantics, you can return a std::tuple1:

    auto myCoolFunction(int myParam1) {
        return std::make_tuple(5, "nice weather", 5.5, myCoolMat);        
    }
    

    If you want to force the types (e.g., have a std::string instead of a const char *):

    std::tuple<int, std::string, double, cv::Mat> myCoolFunction(int myParam1) {
        return {5, "nice weather", 5.5, myCoolMat};
    }
    

    In both cases, you can access the values using std::get:

    auto tup = myCoolFunction(3);
    std::get<0>(tup); // return the first value
    std::get<1>(tup); // return "nice weather"
    

    1 If you have a C++17 compliant compiler, you can make use of template argument deduction and simply return std::tuple{5, "nice weather", 5.5, myCoolMat}.