老版本的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;
}
看,上面的代码是不是就感觉很高大上了。