在我们的遗留代码以及现代代码中,我们使用宏来执行代码生成等出色的解决方案。我们同时使用#和##运算符。
我很好奇其他开发人员如何使用宏来做很酷的事情,如果他们真的使用宏的话。
发布于 2009-03-16 14:40:22
在C语言中,通常会定义宏来获取逐字参数,同时定义函数来透明地获取它的地址。
// could evaluate at compile time if __builtin_sin gets
// special treatment by the compiler
#define sin(x) __builtin_sin(x)
// parentheses avoid substitution by the macro
double (sin)(double arg) {
return sin(arg); // uses the macro
}
int main() {
// uses the macro
printf("%f\n", sin(3.14));
// uses the function
double (*x)(double) = &sin;
// uses the function
printf("%f\n", (sin)(3.14));
}发布于 2009-03-16 14:44:58
还有X Macro惯用法,它对干式和简单的代码生成很有用:
在标题gen.x中使用not defined宏定义了一种表:
/** 1st arg is type , 2nd is field name , 3rd is initial value , 4th is help */
GENX( int , "y" , 1 , "number of ..." );
GENX( float , "z" , 6.3 , "this value sets ..." );
GENX( std::string , "name" , "myname" , "name of ..." );然后他可以在不同的地方使用它,为每个#include定义一个通常不同的定义:
class X
{
public :
void setDefaults()
{
#define GENX( type , member , value , help )\
member = value ;
#include "gen.x"
#undef GENX
}
void help( std::ostream & o )
{
#define GENX( type , member , value , help )\
o << #member << " : " << help << '\n' ;
#include "gen.x"
#undef GENX
}
private :
#define GENX( type , member , value , help )\
type member ;
#include "gen.x"
#undef GENX
}发布于 2009-03-16 13:54:53
最酷的宏是: assert,include guards,__FILE__,__LINE__。
避免在代码中使用其他宏。
编辑:
只有在没有合法解决方案的情况下才使用宏。
https://stackoverflow.com/questions/650461
复制相似问题