考虑一个问题,C++如何实现返回多个值?如何标记其中一个bool返回值用于记录函数运行状态?
我们可以通过pair或tuple实现,有以下代码:
#include <iostream> #include <string> using namespace std; struct ss { string s; int size; }; pair<bool, ss> func2(const string& in) { ss a{"", -1}; if (in.size() == 0) return { false, a }; a.s = in; a.size = in.size(); return { true, a }; } int main() { if (auto [status, a] = func2("yeah"); status) { cout << a.s << " " << a.size << endl; } return 0; }
可以通过C++17的新特性optional省去bool值,简化上述代码:
#include <iostream> #include <string> #include <optional> using namespace std; struct ss { string s; int size; }; optional<ss> func3(const string& in) { ss a{ "", -1 }; if (in.size() == 0) return nullopt; a.s = in; a.size = in.size(); return { a }; } int main() { if (auto ret = func3("yeah"); ret.has_value()) { cout << ret->s << " " << ret->size << endl; } return 0; }
源代码:
#include <iostream> #include <string> #include <optional> using namespace std; struct ss { string s; int size; }; /* tuple<bool, string, string> func(const string& in) { if (in.size() == 0) return make_tuple(false, "", ""); return make_tuple(true, in, "123654"); }*/ pair<bool, ss> func2(const string& in) { ss a{"", -1}; if (in.size() == 0) return { false, a }; a.s = in; a.size = in.size(); return { true, a }; } optional<ss> func3(const string& in) { ss a{ "", -1 }; if (in.size() == 0) return nullopt; a.s = in; a.size = in.size(); return { a }; } int main() { /* tuple<int, double, string> r{ 12, 128.33, "happy~" }; auto r2 = make_tuple( 12, 128.33, string("happy~") ); //tuple<int, double, string> r2 //Structured Bindings if (auto [status, out1, out2] = func("unhappy!!!"); status) { cout << out1 << endl; cout << out2 << endl; }*/ if (auto [status, a] = func2("yeah"); status) { cout << a.s << " " << a.size << endl; } if (auto ret = func3("yeah"); ret.has_value()) { cout << ret->s << " " << ret->size << endl; } return 0; }
执行结果:
yeah 4 yeah 4
原文:https://zhuanlan.zhihu.com/p/64985296
标签:std,return,string,17,tuple,ss,include,optional,size From: https://www.cnblogs.com/karinto/p/17283350.html