C++内联闭包类似

C++ inline closure analogue

本文关键字:闭包 C++      更新时间:2023-10-16

函数执行某个代码块两次:cnt=0和cnt=1。目前我使用以下实现:

int func {
    int V1, V2, ... , Vn;
    #define cnt 0
        // a block of code: some operations with V1, ... , Vn
    #undef cnt
    #define cnt 1
        // the same block of code
    #undef cnt
}

这个代码很难看。使用内联函数会导致更丑陋的代码:我需要通过引用将所有涉及的变量传递给函数。因此,我想创建某种闭包。

我不能使用这样的东西

struct Nested {
    __forceinline void block(const int cnt) {
        // block of code
    };
};

因为V1,出于性能原因,不应将Vn设置为静态。

我尝试使用lambda函数,但Visual C++2013未能内联它,即使内联设置为"Any Fitness(/Ob2)"(即使使用PGO),这也会影响性能。

有什么建议吗?

您可以这样做:

struct func_impl
{
  int V1, V2, ..., Vn;
  int res;
  template <int cnt>
  void blockOfCode() {
    ...
  }
};
int func()
{
  func_impl f;
  f.blockOfCode<0>();
  f.blockOfCode<1>();
  return f;
}

这应该相当于您的#define解决方案。

EDIT在评论中,您提到您还有var ## cnt等变量。这些可以用一个双元素数组代替,使用模板参数cnt对它们进行索引:

int var[2];
var[cnt] = ...;