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 the content is about a more specific topic never covered on Stackoverflow I would like the question to be reopened. This happened now, so here goes the question.
I have given a function expecting three integer values as parameters length(int x, int y, int z);. I cannot modify this function, e.g. to accept a struct or tuple of whatever as single parameter.
Is there a way in C++ to write another function which can be used as single argument to the function above, like length(arguments());?
Anyhow the return type of that function arguments(); seems to need to be int, int, int. But as far as far as I know I can’t define and use functions like this in C++. I know that I could return a list, a tuple, a struct or a class by arguments(). The question was closed because some people thought I would have asked about this. But the difficult part is to pass the tuple, or struct, or whatever as the three given integer parameters.
Is this possible and if yes, how is that possible in C++? A solution making use of C++11 would be fine.
I don’t think there is any direct way of doing what you want, but here is a C++11 technique that I use in several places of my code. The basic idea is to use a template function which I’ve called
call_on_tupleto take a function argumentfas well as a tuple of further arguments, expand the tuple and call the function on the expanded list of arguments:So the idea is that instead of calling
you would call
This assumes that
arguments()is changed so it returns astd::tuple<int,int,int>(this is basically the idea from the question you cited).Now the difficult part is how to get the
Is...argument pack, which is a pack of integers0,1,2,...used to number the elements of the tuple.If you are sure you’ll always have three arguments, you could use
0,1,2literally, but if the ambition is to make this work for any n-ary function, we need another trick, which has been described by other posts, for example in several answers to this post.It’s a trick to transform the number of arguments, i.e.
sizeof...(Args)into a list of integers0,1,...,sizeof...(Args):I’ll put this trick and the implementation of
call_on_tuplein a namespacedetail:Now the actual function
call_on_tupleis defined in global namespace like this:It basically calls
detail::index_makerto generate the list of increasing integers and then callsdetail::call_on_tuplewith that.As a result, you can do this:
which is hopefully close enough to what you needed.
Note. I have also added an
enable_ifto ensure this is only used with functionsfthat actually return a value. You can readily make another implementation for functions that returnvoid.Sorry again for closing your question prematurely.
PS. You’ll need to add the following include statements to test this: