【问题标题】:C++ vector of lambdas - undefined referenceslambda 的 C++ 向量 - 未定义的引用
【发布时间】:2017-09-23 13:38:55
【问题描述】:

我试图在 lambdas 中包装几个构造函数,以便将它们存储在一个向量中,然后循环遍历它:

using move_constructor = std::function<Move*(Site,vector<Move*>*, int)>;

vector<move_constructor> diff_plane_list = {
  [](Site p_site, vector<Move*>* move_list, int latLen) {
    return new Diffuse_inplane_px(p_site, move_list, latLen);
  },
  [](Site p_site, vector<Move*>* move_list, int latLen) {
    return new Diffuse_inplane_mx(p_site, move_list, latLen);
  },
  ...
}

但是,当尝试使用 g++-5.3 对其进行编译时,对于向量中的每个项目,我都会收到以下错误消息:

/tmp/ccc2A87Z.o: In function `{lambda(std::tuple<int, int, int>, std::vector<Move*, std::allocator<Move*> >*, int)#1}::operator()(std::tuple<int, int, int>, std::vector<Move*, std::allocator<Move*> >*, int) const':
All_moves.cc:(.text+0x5e): undefined reference to `Diffuse_inplane_px::Diffuse_inplane_px(std::tuple<int, int, int>, std::vector<Move*, std::allocator<Move*> >*, int)'

所以vector&lt;Move*&gt;* 以某种方式转换为vector&lt;Move*, std::allocator&lt;Move*&gt; &gt;*? 我应该如何正确地做到这一点?有没有更好的方法来遍历构造函数列表并将指向已创建对象的指针存储在向量中?

【问题讨论】:

  • "undefined reference":您没有提供指定Diffuse_inplane_px构造函数的定义。
  • 顺便说一句,最好返回 std::unique_ptr&lt;Move&gt; 而不是原始的拥有指针。 (并创建您的make_unique,因为您没有 C++14)。

标签: c++ c++11 vector lambda


【解决方案1】:

“未定义的引用”:您没有提供指定 Diffuse_inplane_px 构造函数的定义。

提供一个并确保它与项目相关联。

【讨论】:

  • 是的,gcc 要我指定构造函数Diffuse_inplane_px(std::tuple&lt;int, int, int&gt;, std::vector&lt;Move*, std::allocator&lt;Move*&gt; &gt;*, int),我不明白为什么第二个参数必须是vector&lt;Move*, std::allocator&lt;Move*&gt; &gt;*,而不是vector&lt;Move*&gt;*。 lambda 的参数就是这种类型,它也在move_constructor 的定义中指定。使用此类型作为第二个参数的构造函数在不同的链接文件中指定。
  • std::vector 具有默认模板参数,因此vector&lt;Move*&gt;vector&lt;Move*, std::allocator&lt;Move*&gt;&gt; 相同。您只需提供Diffuse_inplane_px(Site, std::vector&lt;Move*&gt;*, int)
猜你喜欢
  • 1970-01-01
  • 2016-05-09
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
  • 2020-08-04
相关资源
最近更新 更多