将闭包存储在数组中

store closures in an array

我想在数组中存储一些闭包。 我标记了问题 MSVC10,因为根据 c++11,闭包似乎应该与函数指针兼容(至少在某些情况下),但 MSVC10 不支持。

有没有办法绕过这个限制?

示例:

  typedef double (*Func)(const C* c);

  struct Feature{
    Feature(FeatureId i_id = None, const QString& i_name=QString(), Func i_ex = nullptr)
      :id(i_id),name(i_name), extraction(i_ex)
    {}
    FeatureId id;
    QString   name;
    Func      extraction;
  };

  QList<Feature> features;

  features.append(Feature(feat_t, "a/t", [](const C* c) -> double{return c->a.t;} ));

我希望能够将闭包分配给函数指针,因为我不想定义许多单独的函数。

提前感谢您的建议。

您应该使用 std::function<double(const C*)>(参见 this)而不是 Func,因此

 struct Feature{
    FeatureId id;
    QString name;
    std::function<double(const C*)> extraction;
   /// etc...
 };

您可能需要升级编译器(我猜 Visual Studio 2010 出现在 之前 C++11 standard, but I never used Windows or other Microsoft products). Did you consider using a recent GCC (4.9 at least) or a recent Clang/LLVM (3.5) ?

如果无法升级编译器,请坚持使用 C++98,不要使用 C++11 功能。

根据定义,closure 比函数指针更重,因为它包含 封闭值 (其中一些可能是隐藏的或不明显的)。