I need to take an array of input arguments of size n and bind its values to another function that takes n arguments.
I tried using bind to pass the elements of the array one by one to the function but it didn't work (kind of like using bind_front inside a loop).
What I need is something like:
#include <iostream>
#include <functional>
using namespace std;
int addThreeNumbers(int a, int b, int c)
{
return a+b+c;
}
int main()
{
int parameters[] = {1, 2, 3};
auto f = addThreeNumbers;
// Bind each element from the list one by one
for(int i=1; i<parametersLength; i++)
{
f = bind(f, parameters[i]);
}
f(); // call addThreeNumbers
return 0;
}
The solution would need to work with parameters being an array of any size. Is this possible to do using c++ 11?
Edit
I got it working thanks to Aconcagua and Philipp Lenk! Here is the working code:
#include <iostream>
#include <functional>
using namespace std;
// index sequence only
template <size_t ...>
struct indexSequence
{ };
template <size_t N, size_t ... Next>
struct indexSequenceHelper : public indexSequenceHelper<N-1U, N-1U, Next...>
{ };
template <size_t ... Next>
struct indexSequenceHelper<0U, Next ... >
{ using type = indexSequence<Next ... >; };
template <size_t N>
using makeIndexSequence = typename indexSequenceHelper<N>::type;
int addThreeNumbers(int a, int b, int c)
{
return a+b+c;
}
template <typename F, typename T, size_t N, size_t ... I>
auto dispatch(F function, T(&array)[N], indexSequence<I ...>) -> decltype(function(array[I]...))
{
return function(array[I]...);
}
template <typename F, typename T, size_t N>
auto dispatch(F function, T(&array)[N]) -> decltype(dispatch(function, array, makeIndexSequence<N>()))
{
return dispatch(function, array, makeIndexSequence<N>());
}
int main()
{
int a[] = { 1, 2, 3 };
int s = dispatch(addThreeNumbers, a);
cout << s << endl;
return 0;
}
Edit2
Got it working using tuples as well:
#include <iostream>
#include <tuple>
#include <string>
using namespace std;
// index sequence only
template <size_t ...>
struct indexSequence
{ };
template <size_t N, size_t ... Next>
struct indexSequenceHelper : public indexSequenceHelper<N-1U, N-1U, Next...>
{ };
template <size_t ... Next>
struct indexSequenceHelper<0U, Next ... >
{ using type = indexSequence<Next ... >; };
template <size_t N>
using makeIndexSequence = typename indexSequenceHelper<N>::type;
template <class F, class Tuple, std::size_t... Is>
constexpr auto apply_impl(const F& f, Tuple t, indexSequence<Is...>) -> decltype(f(std::get<Is>(t)...))
{
return f(std::get<Is>(t)...);
}
template <class F, class Tuple>
constexpr auto apply(const F& f, Tuple t) -> decltype(apply_impl(f, t, makeIndexSequence<std::tuple_size<Tuple>{}>{}))
{
return apply_impl(f, t, makeIndexSequence<std::tuple_size<Tuple>{}>{});
}
int sum(int a, int b, string c)
{
cout << c << endl;
return a+b;
}
int main()
{
auto parameters = std::make_tuple(1,2,"1+2=3");
int s = apply(sum, parameters);
cout << s << endl;
return 0;
}