Home Use pack parameter in template vector & Lambda - c++
Reply: 0

Use pack parameter in template vector & Lambda - c++

user2274 Published in May 25, 2018, 8:58 am

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){
    [&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);


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;


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){
  [&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 ..

  1. 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

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.369161 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO