use*_*798 1 c++ closures inline
函数执行两次代码块:对于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
}
Run Code Online (Sandbox Code Playgroud)
这段代码非常难看.使用内联函数会导致更加丑陋的代码:我需要通过引用将所有涉及的变量传递给函数.因此,我想创建一些封闭.
我不能用类似的东西
struct Nested {
__forceinline void block(const int cnt) {
// block of code
};
};
Run Code Online (Sandbox Code Playgroud)
因为性能原因,不应将V1,...,Vn设为静态.
我尝试使用lambda函数,但即使内联设置为"Any Suitable(/ Ob2)"(即使使用PGO),Visual C++ 2013也无法内联它,这也会损害性能.
有什么建议?
你可以这样做:
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;
}
Run Code Online (Sandbox Code Playgroud)
这应该等同于您的#define解决方案.
编辑在评论中,你提到你也有变量var ## cnt.这些可以用两元素数组替换,使用template参数cnt来索引它们:
int var[2];
var[cnt] = ...;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
154 次 |
| 最近记录: |