Writing function that returns two types

Oct 22, 2012 at 12:55pm
Hi all!

I have written a function that returns a string. It works as expected. It looks like this:

1
2
3
4
5
6
7
8
string myFunction (int i, string myString) {
  string output;
  if (everything==ok) {
      return output;
  } else {
      return "Error";
  }
}


Now, if the function fails, I'd rather like to send an integer. How should I do that? Is it possible?

I've read many posts where some people would suggest that I could pass an integer variable as reference and write that variable if the function fails or even pass a struct as reference and use it in such a way as well.

I just want to know what do you people think is the most appropriate (or elegant) way of doing it. Is there may be another way?

Thanks in advance!

BR,

Lucas
Oct 22, 2012 at 1:07pm
You could throw an exception (although it's best to throw something derived from std::exception rather than a plain integer)
Last edited on Oct 22, 2012 at 1:09pm
Oct 22, 2012 at 1:26pm
One way of doing it is pass the output type by reference, in this case a string, and return error code.
In case if no error return 0, in case or error return the error code.
Oct 22, 2012 at 4:03pm
In addition to passing the return value as a reference type parameter, you can also return a struct type.
1
2
3
4
5
6
7
8
9
10
11
12
13
typedef struct Result
{
    int errorCode;
    string value;
}
Result;

Result myFunction()
{
    Result result;
    // some code here
    return (result);
}


Not really my preferred solution, but it's good to know alternatives.
Oct 22, 2012 at 6:22pm
As a variation on vince1027's suggestion, you could return a pair (std::pair)

1
2
3
4
5
6
7
8
pair<string, int> myFunction (int i, string myString) {
  string output;
  if (everything==ok) {
      return make_pair(output, 0);
  } else {
      return make_pair("Error", 666);
  }
}


This trick is used by some STL functions, e.g. map::insert (the overload which inserts a value)

But I would go for either codewalker's reference solution or Cubbi's exception based one.

Note I would generally avoid the exception based solution in cases where the error was not rare/unexpected.

Andy
Last edited on Oct 22, 2012 at 10:51pm
Topic archived. No new replies allowed.