簡體   English   中英

在模板向量和 Lambda 中使用 pack 參數 - C++

[英]Use pack parameter in template vector & Lambda - c++

我正在使用向量在 lambda 函數中嘗試可變參數模板包。 學習c++編程語言書,說“如果您需要捕獲可變參數模板參數,請使用...”(舉一個簡單的例子)。

我無法編譯它,我的目標只是能夠在我的 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);
}

堆棧跟蹤:

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;

問候

更新 1:

好的,所以我更新了這個問題以添加我與他的建議合並的 Stroustrup 的兩個代碼。

Lambda 和向量

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');}
}

使用 lambda 的版本顯然是贏家。 但是如果你真的想要一個名字,你可以只提供一個..

  1. 捕獲模板

如果您需要捕獲模板參數,請使用 ... 例如:

template<typename... Var>
void algo(int s, Var... v){
  auto helper = [&s,&v...]{return s*(h1(v...)+h2(v...);)};
}

h1 & h2 是簡單的示例函數

我會盡量解釋你的代碼有什么問題,但要真正理解,你需要閱讀一些好書

  • std::vector是一個同類容器,它的所有元素都只有一個相同的類型。 這個vector<vectType...>毫無意義。 例如, std::vector<int>具有所有int元素; 沒有這樣的東西std::vector<int, double, short> 因此,如果您想打印某些不同類型的typeid ,那么您的方法從一開始就是錯誤的。

  • 在您自己的代碼[&vectType...] ,那些vectTypetypes ,這也是毫無意義的。 在您引用的代碼[&s,&v...] ,那些vvariables ,因此是正確的。

  • 這樣的vectType... v; 聲明是你自己發明的,不是C++。

如果您想以通用方式打印變量的typeid ,以下是C++14一個簡單示例:

#include <iostream>

template<class... Args>
void print_all_typeid(Args const &...args)
{
    auto dumb = [] (auto... x) {};
    auto printer = [] (auto const &x) {
        std::cout << typeid(x).name() << "\n";
        return true;
    };

    dumb(printer(args)...);
}

int main() {
    print_all_typeid(std::cin, 12, std::cout, 1L, 2.0, 3.f);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM