简单介绍
老版本的 C++函数返回值都是只有一个内嵌类型或者自定义类型。所以 以前 我们如果想要返回多个值,就必须将其封装为 struct, 然后在将其返回。 但是 C++17 引入了 Structured Bindlings 这个特性。他是通过 std::tuple, std::pair, std::array, and aggregate structures 来实现多个返回值。
下面来个例子, 更加直观的欣赏 C++17 的魅力:
#include <iostream>
#include <string>
#include <tuple>
template <class T>
std::tuple<bool, std::string> testStructBinding(const T& doc) {
if (doc){
return {true, std::string("doc is true")};
} else {
return {false, std::string("doc is false")};
}
}
int main(){
bool doc = true;
auto[testFlag, description] = testStructBinding(doc);
std::cout << "testFlag :" << testFlag << " description :" << description << std::endl;
return 0;
}
总结
现在看看,上面的代码是不是就感觉很高大上了。咱们 C++也能返回多返回值了!