C++内联闭包类似
C++ inline closure analogue
函数执行某个代码块两次: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] = ...;
相关文章:
- 如何将C++闭包与变量参数同时重用——类似于JavaScript
- C++中的 JavaScript 样式闭包
- 如何使用类模拟 C++11 中的 lambda 函数和闭包?
- 使用带有闭包的 lambda 的回调
- C++中的 Lambda <-> 闭包等价性
- 为什么 std::remove_if 会创建如此多的闭包?
- Lambda闭包左值可以作为右值参考参数传递
- 如何声明接受字符串、返回void的闭包的类型
- 添加了闭包的 Perl newXS()
- 具有意外结果的 C++ 闭包
- 关于函数模板中定义的 lambda 闭包类型可以说些什么?
- 基类如何调用派生类在 c++ 中传递的闭包?
- 通过引用将自定义结构的向量传递给 boost::compute 闭包或函数
- 创建特征以检测C++中的闭包类型
- 在 c++ 中使用函数装饰器(使用闭包)时出现意外的分段错误
- Lambda 表达式闭包函数不起作用
- Lambda 闭包类型构造函数
- 在闭包中,如何通过存储在内存中的指针或引用类型捕获可变性或用现代函数式语言进行处理?
- boost::compute,将指针传递给闭包
- 没有声明和初始化的类似闭包的函数(即没有'auto f = make_closure();')