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

Any straightforward way to capture and initialize multiple return values from function

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

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

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

我知道使用 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 类似?)。