c ++循环宏 [英] c++ loop macros
问题描述
我使用宏编码展开循环,如下所示:(傻的例子)
#define foreach_small_prime(p,instr){ \
int p; \
p = 2; INSTR; \
p = 3; INSTR; \
p = 5; INSTR; \
p = 7; INSTR; \
}
foreach_small_prime(pp,cout<< pp);
int sum = 0;
foreach_small_prime(pp,{
sum + = pp;
if(sum> = 10)cout << sum< endl;
});
但在某些情况下,我可能会使用构造:
$ b $ (int ii = 0; ii< 20; ii + = 2)
int sum = 0;
foreach_small_even(pp){
sum + = pp;
if(sum> = 10)cout<<总和<< ENDL;
$ b我喜欢这个宏,因为我可以传递一个变量 name em>作为参数。
问题:有没有像第二个宏那样的像第一个宏一样定义循环的方法? b $ b
您可以查看Boost 预处理器库。它可以做各种循环的事情。语法不是很好,但我相信它的作品。但是,我自己并没有使用它。
I use macros to code unrolled loops like this: (silly example)
#define foreach_small_prime(p, instr) { \
int p; \
p = 2; instr; \
p = 3; instr; \
p = 5; instr; \
p = 7; instr; \
}
foreach_small_prime(pp, cout << pp);
int sum = 0;
foreach_small_prime(pp, {
sum += pp;
if (sum >= 10) cout << sum << endl;
});
But in some cases I might use for construct:
#define foreach_small_even(ii) for(int ii = 0; ii < 20; ii += 2)
int sum = 0;
foreach_small_even(pp) {
sum += pp;
if (sum >= 10) cout << sum << endl;
}
I like this macros because I can pass a variable name as a parameter.
Question: Is there a way to define loop like the first one in a for-like syntax like the second macro?
You could check out the Boost preprocessor library. It can do all sorts of looping things. The syntax isn't great, but I believe it works. I have not used it myself, however.
这篇关于c ++循环宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!