Humam Helfawi Humam Helfawi - 3 months ago 8
C++ Question

Get set of arguments as result of a function

I do not know the name of this pattern or even if it is exist. I need a function that return a set of arguments that would be used in another function. For example, I have this function:

void foo(int a, float b, some_class c);


I want to write a function like this:

//Theoretical code:
arguments get_arguments(){
return arguments(0,0.0f, some_class());
}


Then call
foo
like this:

foo(get_arguments());


Is this possible? if yes,How?

Answer

get_arguments can be implemented with std::make_tuple:

auto get_arguments(){
    return std::make_tuple(0,0.0f, some_class());
}

This will return a std::tuple<int,float,some_class>.

You can call foo with the arguments using std::experimental::apply from C++17:

std::experimental::apply(foo, get_arguments());

Live Demo

There is an implementation of std::experimental::apply here if you need one.


To clean up the call, you could add a forwarding function:

template <typename Tuple>
void foo(Tuple&& t) {
    return std::experimental::apply(
        static_cast<void(*)(int,float,some_class)>(&foo),
        std::forward<Tuple>(t));
}

Then you can use the syntax you desire:

foo(get_arguments());

Live Demo

Comments