[英]Defining Exponential Preprocessor Macro
我計划在幾個月內參加編程競賽,我想定義一些宏以最小化我需要做的輸入。 有人告訴我,將數字提高到冪足以從中受益。 我只需要它與整數參數一起工作(盡管參數本身可能是表達式)。 我嘗試了幾種不同的變體,但無法獲得正確的語法。
/* c is where the result is stored */
#define EXP(a,b,c) c=a; for (int ii=0; ii<(b)-1; c*=(a), ii++);
這可行,但是我不能在像function( EXP(a,b,c) );
這樣的表達式中使用function( EXP(a,b,c) );
我要做
int result;
EXP(a,b,result);
function(result);
我認為這可以在表達式內部使用,但無法編譯
#define EXP(a,b) int c=a; for (int ii=0; ii<(b)-1; (c)*=(a), i++); c
與: error: expected primary-expression before 'int'
在以下情況下使用, error: expected primary-expression before 'int'
:
int result = EXP(2,10);
這是我的代表職能:
int EXP(int base, int power) {
int result = base;
for (int ii=0; ii<power-1; ii++)
result *= base;
return result;
}
使用宏功能是錯誤的工具。 不過,您說您認為它可以在表達式內運行 ,請考慮一下一旦預處理器完成工作后,它將如何查找實際的編譯器:
int result = int c=2; for (int ii=0; ii<(10)-1; (c)*=(2), i++); c
無論您多么努力,都無法執行變量定義,也不能在表達式內for
循環。
您可以使用遞歸模板模板方法:
template<int base, unsigned int exp>
struct Pow {
enum { value = base * power<base, exp-1>::value };
};
// stopping condition
template<int base>
struct Pow<base,0> {
enum { value = 1 };
};
並像這樣使用它:
int i = Pow<10,2>::value;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.