Question about function data types

Ok so when you have a function and its going to return a certain data type like an int, you put return blah; but what if the function is returning 2 different data types? how does that work? or needs to return 2 different ones?
You can't return two different data types. Of course there are ways to achieve similar effects (e.g. returning variants or pointers to derived classes). Returning two or more different values, possibly of different types can be achieved by returning a pair or a tuple.
"Returning two or more different values, possibly of different types can be achieved by returning a pair or a tuple."

How do you do that? what does it look like?
closed account (zb0S216C)
Returning multiple objects requires the use of structures. Like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
template <typename TypeA, typename TypeB>
struct Pair 
{
    Pair(TypeA const &init_a, TypeB const &init_b)
        : a(init_a), b(init_b) 
    { }

    TypeA a;
    TypeB b;
};

Pair<int, double> function()
{
    return(Pair<int, double>(10, 3.2));
}

int main()
{
    std::cout << function().a;
    return(0);
}

Wazzak
Last edited on
What does the : at the end of Pair(TypeA const &init_a, TypeB const &init_b) do? and why are there functions after it?
@Framework
Why create a pair class when C++ already has std::pair?
http://www.cplusplus.com/reference/std/utility/pair/

@Ch1156
It's the syntax for initializing the data members of the class.
It might be easier for you to pass dome arguments by reference and store the "return" values in them. Just another way to do this:

1
2
3
4
5
6
7
8
9
10
11
/**
 * @param str: input to be "split"
 * @param head: the first word of str is stored here
 * @param tail: the rest of str is stored here
 */
void split(const string &str, string &head, string &tail) {
    istringstream sin(str); //allows us to read the data in str like it's an istream
    sin >> head; //store the first word of str in head
    tail = sin.str(); //store the leftovers in tail
    //void function, no need for a return statement
}
Last edited on
Topic archived. No new replies allowed.