【问题标题】:Use pack parameter in template vector & Lambda - c++在模板向量和 Lambda 中使用 pack 参数 - c++
【发布时间】:2018-02-10 22:06:45
【问题描述】:

我正在使用向量在 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,lambda捕获,变量声明都是错误的。
  • 谢谢各位cmets,我在他的书里加了Stroustrup的两个例子,其实我是学c++的,所以我也试试我的方法。我只是想连接它的两个例子来测试自己。你能告诉我真正的问题是什么吗?我不认为我离真实如此遥远;我当然想了解我的错误
  • 有人可以帮帮我吗? @liliscent你说的都是错的,我真的不明白你的意思,你在讨论pack参数?

标签: c++ templates lambda variadic-templates


【解决方案1】:

我会尝试解释你的代码有什么问题,但要真正理解,你需要阅读some good books

  • std::vector 是一个同构容器,它的所有元素只有一个相同的类型。这个vector&lt;vectType...&gt; 毫无意义。例如,std::vector&lt;int&gt; 具有所有 int 元素;没有没有这样的事情std::vector&lt;int, double, short&gt;。因此,如果您想为某些不同类型打印typeid,那么您的方法从一开始就是错误的。

  • 在你自己的代码[&amp;vectType...]中,那些vectType类型,这也是没有意义的。在您引用的代码[&amp;s,&amp;v...] 中,那些v变量,因此是正确的。

  • 这种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);
}

【讨论】:

  • 感谢您的建议,正如我在帖子中所说,我正在阅读 Stroustrup 的“c++ 编程语言”。所以我认为这是一本好书(1300页哎哟)我不是初学者,这本书非常好,我从头到尾阅读了它但有时有些东西(如可变参数模板)我不知道只是展示前解释后300页;我认为这是我的误解来自那个事实。
猜你喜欢
  • 1970-01-01
  • 2014-12-13
  • 2019-04-12
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 2018-12-17
  • 2020-10-26
  • 2017-09-10
相关资源
最近更新 更多