I am trying variadic template pack inside lambda function with vector. Learning the c++ programming langage book, it's said "If you need to capture a variadic template argument, use ..." (with a simple example).
I am not able to compile it, my aim is just to be able to print the variadic type inside my lambda:
#include <iostream>
#include <vector>
#include <typeinfo>
using namespace std;
template<typename... vectType>
void printAllElements(vector<vectType...>& nbList, ostream& output, int nbToTest){
for_each(begin(nbList),end(nbList),
[&vectType...](vectType... x){
vectType... v;
output << x << endl;
output << typeid(v).name() << endl;
}
);
}
int main() {
vector<int> myVect {10,20,156,236};
printAllElements(myVect,cout, 4);
}
StackTrace:
learnC++/main.cpp:10:7: error: 'vectType' in capture list does not name a variable
[&vectType...](vectType... x){
^
learnC++/main.cpp:11:15: error: only function and template parameters can be parameter packs
vectType... v;
^
learnC++/main.cpp:12:7: error: variable 'output' cannot be implicitly captured in a lambda with no capture-default specified
output << x << endl;
Regards
Update 1:
Ok so I update this question to add the two code of Stroustrup I concataned with his advices.
Lambda & Vector
Void print_modulo(const vector<int>& v, ostream& os, int m){
for_each(begin(b),end(v),
[&os,m](int x){ if (x%m==0 os << w << '\n');}
}
The version using lambda is a clear winner. But if you really want a name, you can just provide one ..
- Capture template
If you need to capture template argument, use ... For example:
template<typename... Var>
void algo(int s, Var... v){
auto helper = [&s,&v...]{return s*(h1(v...)+h2(v...);)};
}
h1 & h2 are simple examples functions