I am trying to learn about variadic templates in C++11. I have a class which is basically a wrapper around a std::array
. I want to be able to pass function objects (ideally lambdas) to a member function and then have the elements of the std::array
passed on as parameters of the function object.
I have used a static_assert
to check that the number of parameters matches the length of the array but I cannot think of a way to pass the elements as arguments.
Here is the code
#include <iostream>
#include <array>
#include <memory>
#include <initializer_list>
using namespace std;
template<int N, typename T>
struct Container {
template<typename... Ts>
Container(Ts&&... vs) : data{{std::forward<Ts>(vs)...}} {
static_assert(sizeof...(Ts)==N,"Not enough args supplied!");
}
template< typename... Ts>
void doOperation( std::function<void(Ts...)>&& func )
{
static_assert(sizeof...(Ts)==N,"Size of variadic template args does not match array length");
// how can one call func with the entries
// of data as the parameters (in a way generic with N)
}
std::array<T,N> data;
};
int main(void)
{
Container<3,int> cont(1,2,3);
double sum = 0.0;
auto func = [&sum](int x, int y, int z)->void{
sum += x;
sum += y;
sum += z;
};
cont.doOperation(std::function<void(int,int,int)>(func));
cout << sum << endl;
return 0;
}
So my question (as indicated in the code) is how can one pass the entries of data
onto the function func
in a way which is generic with N
?
Bonus Question: Is it possible to do away with the unsightly conversion to std::function
in main and pass in a lambda directly?