Is it possible? Function with specific parameter type but dependable return type

I am trying to create a function that has a specific parameter type but changeable return type.

The pseudo-code might look like this:

1
2
3
4
5
6
7
8
9
10
11
flexible_return_type int_or_string(std::string str) {
    flexible_return_type res;
    
    if (str == "int") {
        res = 123;
    } else if (str == "string") {
        res = "abc";
    }
    
    return res;
}


This would be quite simple in ActionScript 3.0 as I only have to specify the return type to *.

How can I achieve this with C++? I don't believe that templates are a solution.
You could return a variant type:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <boost/variant.hpp>

boost::variant<std::string, int> int_or_string(const std::string& str)
{
    boost::variant<std::string, int> res;

    if (str == "int") {
        res = 123;
    } else if (str == "string") {
        res = "abc";
    }

    return res;
}

int main()
{
    std::cout << "as int: " << int_or_string("int") << '\n'
              << "as string: " << int_or_string("string") << '\n';
}


but it's very rarely needed. What problem are you actually trying to solve?
you problem can be easily solved by using auto returntype
crude ex:

1
2
3
4
5
6
7
8
9
10
auto div(int a,int b)
{
  auto c;
  if( b != 0 ){
  c=a/b;
  }
  else
  c="invalid input values";
  return c;
}


google more on auto keyword.
Last edited on
thanks for the replies!

@Cubbi
what i'm trying to do is that i have a vector containing integers and a vector containing strings.

a function when passed a char and and an integer n returns the nth integer in the vector or the nth string in the other vector. whether it returns the integer or the string depends on the char.

the pseudo code might be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
std::vector ints;
std::vector strs;

return_type int_or_string(char iOs, int n) {
    return_type res;
    
    if (iOs == 'i') {
        res = ints[n];
    } else if (iOs == 's') {
        res = strs[n];
    }
    
    return res;
}
Topic archived. No new replies allowed.