C++ 从函数中捕获和初始化多个返回值的任何简单方法
在我的项目中,很少有函数通过tuple返回多个值,而且它们被大量使用。所以我想知道C++中有什么方法可以捕获和初始化那个函数调用返回的单个值。下面的例子将更好地解释这个问题C++ 从函数中捕获和初始化多个返回值的任何简单方法,c++,templates,c++14,stdtuple,C++,Templates,C++14,Stdtuple,在我的项目中,很少有函数通过tuple返回多个值,而且它们被大量使用。所以我想知道C++中有什么方法可以捕获和初始化那个函数调用返回的单个值。下面的例子将更好地解释这个问题 #include <iostream> #include <string> #include <tuple> std::tuple<std::string,int,int> getStringWithSizeAndCapacity() {
#include <iostream>
#include <string>
#include <tuple>
std::tuple<std::string,int,int> getStringWithSizeAndCapacity()
{
std::string ret = "Hello World !";
return make_tuple(ret,ret.size(),ret.capacity());
}
int main()
{
//First We have to declare variable
std::string s;
int sz,cpcty;
//Then we have to use tie to intialize them with return of function call
tie(s,sz,cpcty) = getStringWithSizeAndCapacity();
std::cout<<s<<" "<<sz<<" "<<cpcty<<std::endl;
//Is there a way in which I can directly get these variables filled from function call
//I don't want to take result in std::tuple because get<0>,get<1> etc. decreases readibility
//Also if I take return value in tuple and then store that in individual variables then I am wasting
//tuple as it will not be used in code
return 0;
}
#包括
#包括
#包括
std::tuple getStringWithSizeAndCapacity()
{
std::string ret=“你好,世界!”;
返回make_tuple(ret,ret.size(),ret.capacity());
}
int main()
{
//首先我们必须声明变量
std::字符串s;
国际深圳,cpcty;
//然后我们必须使用tie来初始化它们,并返回函数调用
tie(s、sz、cpcty)=getStringWithSizeAndCapacity();
标准::cout
有没有一种方法可以直接从函数调用中获取这些变量?我不想在std::tuple中获取结果,因为get、get等会降低可读性
另外,若我在元组中获取返回值,然后将其存储在各个变量中,那个么我就是在浪费元组,因为它不会在代码中使用
我知道使用std::get()
会降低可读性,但您可以尝试通过一些注释来改进它
// get the size of the returned string (position 1)
auto sz = std::get<1>(getStringWithSizeAndCapacity());
如果您希望避免命名未使用的变量(例如,您对容量不感兴趣),可以使用std::ignore
std::string s;
int sz;
std::tie(s,sz,std::ignore) = getStringWithSizeAndCapacity();
不幸的是,std::ignore
不能(据我所知)与新的C++17结构化绑定(可能与C++20类似?)一起使用。现在的绑定有什么问题?看起来很直接。错误的是我的变量未初始化。我通常只为这个结构结果定义结构{std::string s;int sz,cpcty;}
并将其与auto
std::string s;
int sz;
std::tie(s,sz,std::ignore) = getStringWithSizeAndCapacity();