C预处理器:#define一个可以在没有括号的情况下调用的宏
C preprocessor: #define a macro that can be called without parentheses
我想知道是否可以编写一个行为如下的宏:
void Func(int x)
{
printf("%d",x);
}
#define func Func x //or something
int main()
{
func 10; //<---- remove parenthesis
}
在这种情况下,func
将指向真正的函数 Func
,并且 10 将是其不带括号的参数。
我正在尝试实现类似于 C++ 中的 new
运算符但在 C 中的东西。
示例:
class Base* b = new(Base);
在这种情况下,class
是struct
的宏,new
是一个接受函数指针的函数,Base
是一个分配内存的函数struct Base
.
我想将代码重写成这样:
class Base* b = new Base;
如果我能想出一个宏就可以了:)
我不认为你可以为所欲为。如果你有一个带参数的宏,比如#define func(x) Func(x)
,那么你需要像调用函数一样调用它:
#define func(x) Func(x)
func(x) // Will be replaced by Func(x) during pre-processing
如果您有一个没有参数的宏,那么在预处理过程中会简单地替换该值:
#define MY_VAL 110
func(MY_VAL) // Will be replaced by Func (110) during pre-processing
删除第一个支架很容易...
#define func Func(
func 10);
... 完全有效,但很奇怪。不幸的是,我认为没有办法删除右括号。
正如 Joachim Pileborg 在他的评论中指出的那样,我没有看到 好的 理由在真正的 C
程序中这样做。
有趣的是,您可能只需将 new
定义为 (#define new
) 并为每个类似构造函数的函数定义一个标记,该函数会生成带括号的真实函数调用,例如 #define BASE Base()
.
这应该使以下代码合法 C:
#define new
#define class struct
#define BASE Base()
// forward declaration
class Base;
extern class Base *Base();
void f()
{
class Base* b = new BASE;
}
我想知道是否可以编写一个行为如下的宏:
void Func(int x)
{
printf("%d",x);
}
#define func Func x //or something
int main()
{
func 10; //<---- remove parenthesis
}
在这种情况下,func
将指向真正的函数 Func
,并且 10 将是其不带括号的参数。
我正在尝试实现类似于 C++ 中的 new
运算符但在 C 中的东西。
示例:
class Base* b = new(Base);
在这种情况下,class
是struct
的宏,new
是一个接受函数指针的函数,Base
是一个分配内存的函数struct Base
.
我想将代码重写成这样:
class Base* b = new Base;
如果我能想出一个宏就可以了:)
我不认为你可以为所欲为。如果你有一个带参数的宏,比如#define func(x) Func(x)
,那么你需要像调用函数一样调用它:
#define func(x) Func(x)
func(x) // Will be replaced by Func(x) during pre-processing
如果您有一个没有参数的宏,那么在预处理过程中会简单地替换该值:
#define MY_VAL 110
func(MY_VAL) // Will be replaced by Func (110) during pre-processing
删除第一个支架很容易...
#define func Func(
func 10);
... 完全有效,但很奇怪。不幸的是,我认为没有办法删除右括号。
正如 Joachim Pileborg 在他的评论中指出的那样,我没有看到 好的 理由在真正的 C
程序中这样做。
有趣的是,您可能只需将 new
定义为 (#define new
) 并为每个类似构造函数的函数定义一个标记,该函数会生成带括号的真实函数调用,例如 #define BASE Base()
.
这应该使以下代码合法 C:
#define new
#define class struct
#define BASE Base()
// forward declaration
class Base;
extern class Base *Base();
void f()
{
class Base* b = new BASE;
}