我想做如下的功能:
list<string> or list<std::pair<string, string>> get(int a){
list<string> a;
list<std::pair<string, string>> b;
if(a == 1)
return a;
else
return b;
}
实现上述功能的最佳方法是什么?
最佳答案
你不能。 C++ 是静态类型,这意味着您无法在运行时更改函数的返回类型。
但是您可以使用元组做一些事情,尽管您需要确定事件成员:
std::tuple<list<string>, list<std::pair<string, string>>> x_y_problem()
{
return std::make_tuple/*ToDo populate as you need*/
}
在调用站点:
list<string> x;
list<std::pair<string, string>> y;
std::tie(x, y) = x_y_problem();
引用:http://en.cppreference.com/w/cpp/utility/tuple/make_tuple
关于C++ 在 lists<string> 和 list<std::pair<string, string>> 之间选择返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46192735/