我想在 C++ 中用不同的参数值做一些重载。
像Python之类的动态语言:
def foo(str):
if str == "a":
return str
if str == "b":
return true
if str == "c":
return 1
C++ 中是否有某种 RTTI 模式使其工作?
Boost::any 在调用函数时需要隐式定义类型:
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;
如果你真的希望在运行时选择正确的类型,那么函数的结果类型静态地是它可以返回的类型的 union ;这可以用 boost::variant
清楚地表达(这是标记 union 的语法糖):
auto foo(std::string const&) -> boost::variant<bool, int, std::string>;
当然是指结果啦boost::variant<bool, int, std::string>
而不是这三个中的任何一个;这正是我们想要的。然后由用户检查实际类型,如果您阅读文档,您会发现有多种方法可以这样做。
关于c++ - C++中如何根据参数的值返回不同的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20029099/