从函数捕获和初始化多个返回值的任何直接方法

时间:2019-01-26 15:25:38

标签: c++ templates c++14 stdtuple

在我的项目中,很少有函数在元组的帮助下返回多个值,并且它们被大量使用。所以我只想知道c ++中有什么方法可以捕获和初始化该函数调用返回的单个值。下面的示例将更好地解释这个问题

    #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;
    }

1 个答案:

答案 0 :(得分:2)

  

有没有一种方法可以直接从函数调用中填充这些变量,我不想在std :: tuple中获取结果,因为get <0>,get <1>等会降低可读性

     

如果我将返回值存储在元组中,然后将其存储在单个变量中,那我就是在浪费元组,因为它不会在代码中使用

我了解使用std::get<>()会降低可读性,但是您可以尝试通过添加一些注释来改善它

// get the size of the returned string (position 1)
auto sz = std::get<1>(getStringWithSizeAndCapacity());

无论如何,在我看来,提高可读性的正确方法是使用std::tie(),但我不清楚它对您有什么问题,或者(从C ++ 17开始)结构化绑定声明

auto [ s, sz, cpcty ] = getStringWithSizeAndCapacity();

如果要避免命名未使用的变量(例如,您对容量不感兴趣),可以使用std::ignore

std::string s;
int sz;

std::tie(s,sz,std::ignore) = getStringWithSizeAndCapacity();

不幸的是,据我所知std::ignore不能用于新的C ++ 17结构化绑定(也许与C ++ 20类似?)。