如何根据C++中参数的值返回不同的类型

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

本文关键字:返回 类型 参数 何根 C++      更新时间:2023-10-16

我想在C++中用不同的参数值做一些重载。

像动态语言,如Python:

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

C++中是否有某种RTTI模式来使其工作?

Boost::

调用函数时隐含定义类型的任何需求:

boost::any foo() {...}
auto result = boost::any_cast<int>(foo("c"));

如何在不隐式给出"int"的情况下定义结果变量?

换句话说,我想在下面做这个语义:

result = foo("a")

有两种语言可以满足你的要求:

  • 动态语言
  • 依赖类型语言

C++两者都不是:函数签名从不依赖于传递给它的参数的值。但是,这可能取决于参数的类型或非类型模板参数的值:

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

如果你真的希望运行时选择正确的类型,那么函数的结果类型是它可以返回的类型的并集;这可以使用boost::variant(这是标记联合的语法糖)干净地表达:

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

当然,这意味着它boost::variant<bool, int, std::string>的结果,而不是这三者中的任何一个;这正是我们想要的。然后由用户检查实际类型,如果您阅读文档,您将看到有多种方法可以做到这一点。

我认为最好的方法是在带有类型字段的结构中使用联合。

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;
};
当你设置var时,

你还必须设置类型,当你得到这个作为返回值时,你应该检查类型并根据它获取var。