博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++ 函数返回多个值
阅读量:3575 次
发布时间:2019-05-20

本文共 2069 字,大约阅读时间需要 6 分钟。

#include 
#include
#include
#include
#include
#include
#include
// C++ return multiple value// 1.returned value,reference parameterbool func(const std::string& in,std::string& out1,std::string& out2){ if(in.size() == 0) return false; out1 = "hello"; out2 = "world"; return true;}// 2.tuplestd::tuple
func(const std::string& in){ if(in.size() == 0) return std::make_tuple(false,"",""); return std::make_tuple(true,"hello0","world0");}// 3.pairnamespace pair{ struct Out{ std::string out1{ }; std::string out2{ }; };}std::pair
func1(const std::string& in){ pair::Out o; if(in.size() == 0){ return { false,o};} o.out1 = "hello1"; o.out2 = "world1"; return { true,o};}// 4.optionalstd::optional
func2(const std::string& in){ pair::Out o; if(in.size() == 0) return std::nullopt; o.out1 = "hello2"; o.out2 = "world2"; return { o};}// 5.variantstd::variant
func3(const std::string& in){ std::variant
re; if(in.size() == 0){ re = bool{ }; }else{ pair::Out o; o.out1 = "hello3"; o.out2 = "world3"; re = o; } return { re};}// 6. anystd::any func4(const std::string& in){ if(in.size() == 0) return bool{ }; pair::Out o; o.out1 = "hello4"; o.out2 = "world4"; return { o};}int main(){ std::string s1,s2; int status = func("hi",s1,s2); if(status){ std::cout <
<< std::endl; std::cout <
<< std::endl; } //tuple返回,结构化绑定 c++17 if(auto [status,out1,out2] = func("hi");status){ std::cout <
<< std::endl; std::cout <
<< std::endl; } //pair返回,结构化绑定 if(auto [status,o] = func1("hi");status){ std::cout << o.out1 << std::endl; std::cout << o.out2 << std::endl; } //optional 返回 if(auto ret = func2("hi");ret.has_value()){ std::cout <
out1<< std::endl; std::cout <
out2<< std::endl; } //variant if(auto ret = func3("hi");!std::get_if
(&ret)){ std::cout <
(ret).out1 << std::endl; std::cout <
(ret).out2 << std::endl; } //any if(auto ret = func4("hi");ret.type() != typeid(bool)){ auto o = std::any_cast
(ret); std::cout << o.out1 << std::endl; std::cout << o.out2 << std::endl; }}

此篇主要涉及到 C++17,如有疑问请留言或者参考。

转载地址:http://xjxgj.baihongyu.com/

你可能感兴趣的文章
Cache模拟器的实现
查看>>
设计模式七大原则
查看>>
SpringBoot入门(二)场景启动器
查看>>
SpringBoot入门--自动配置
查看>>
自动配置原理
查看>>
TCP协议
查看>>
关于Linux系统使用遇到的问题-1:vi 打开只读(readonly)文件如何退出保存?
查看>>
spring注解版(一)
查看>>
SpringBoot中访问控制层(controller)得不到Json数据
查看>>
BFC(Block Formatting Context)
查看>>
什么是作用域,什么是闭包,什么是作用域链
查看>>
惰性求值,面向对象
查看>>
数据结构之列表
查看>>
es5中的arguments对象
查看>>
git本地仓库和远程仓库关联,分支重命名
查看>>
js对象的深拷贝,你真的觉得很简单吗?
查看>>
你真的了解map方法吗?手动实现数组map方法。
查看>>
带你手动实现call方法,让你收获满满
查看>>
前端知识体系
查看>>
使用join查询方式找出没有分类的电影id以及名称
查看>>