xunzhang
xunzhang

Reputation: 2936

How can I return different type according to the value of parameter in C++?

I want to do something overload with different value of parameter in C++.

Something like dynamic language such as Python:

def foo(str):
  if str == "a":
    return str
  if str == "b":
    return true
  if str == "c":
    return 1

Is there some pattern of RTTI in C++ to make it work?

Boost::any needs implict define type when call the function:

boost::any foo() {...}

auto result = boost::any_cast<int>(foo("c"));

How can I define result var without implict give 'int'?

In other words, I want to make this semantics below:

result = foo("a")

Upvotes: 1

Views: 409

Answers (2)

Matthieu M.
Matthieu M.

Reputation: 300349

There are two kinds of languages that allow what you are asking for:

  • dynamic languages
  • dependently typed languages

C++ is neither: a function signature never depends upon the value of the arguments passed to it. It may, however, depend on the type of the arguments or the value of non-type template parameters:

struct A{}; struct B{}; struct C{};

auto foo(A) -> std::string;
auto foo(B) -> bool;
auto foo(C) -> int;

If you really wish a runtime choice of the right type, then statically the result type of the function is the union of the types it can return; this can be expressed cleanly using boost::variant (which is syntactic sugar for a tagged union):

auto foo(std::string const&) -> boost::variant<bool, int, std::string>;

Of course, it means the result it boost::variant<bool, int, std::string> and not either one of those three; which is exactly what we want. It is then up to the user to check the actual type, and if you read the documentation you'll see there are multiple ways of doing so.

Upvotes: 1

SHR
SHR

Reputation: 8333

I think the best way is to use a union inside a struct with a type field.

enum var_type{X_BOOL,X_INT,X_DOUBLE,X_STRING /*add more if needed*/};

struct var{
  var_type type;
  union{
    bool bool_var;
    int int_var;
    double dbl_var;
    string str_var;
    /*add more here if needed...*/
  }var;
};

when you set the var you have to set also the type, and when you get this as return value, you should check the type and take the var according to it.

Upvotes: 0

Related Questions