Return several arguments for another function by a single function

前端 未结 6 2017
余生分开走
余生分开走 2021-01-03 05:31

This question was closed as exact duplicate since I chose a misleading question title. It was not wrong but suggested an issue often discussed, e.g. in this question. Since

6条回答
  •  青春惊慌失措
    2021-01-03 05:36

    It is not possible, C++ does not allow to provide 3 return values natively that can be used as 3 separate input arguments for another function.

    But there are 'tricks' to return multiple values. Although none of these provide a perfect solution for your question, as they are not able to be used as a single argument to length() without modifying length().

    Use a container object, like a struct, tuple or class

    typedef struct { int a,b,c; } myContainer;
    
    myContainer arguments(int x, int y, int z) {
      myContainer result;
      result.a = 1;
      // etc
      return result;
    }
    
    myContainer c = arguments(x, y, z);
    length(c.a, c.b, c.c);
    

    The trick is to overload the length() function, so it looks like you can use it with a single argument:

    void length(myContainer c) {
      length(c.a, c.b, c.c);
    }
    
    length(arguments());
    

    Of course you could optimize it further, by using inline, macros, and what not.

    I know it is still not exactly what you want, but I think this is the closest approach.

提交回复
热议问题