如何针对每个宏值执行不同的操作?
#define TYPE char *
if TYPE is char *
do A
if TYPE is int
do B
有没有例子如何做这样的事情?
#define TYPE char *
if TYPE is char *
do A
if TYPE is int
do B
Is there an example how to do such things?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
C 预处理器 MACROS 操作文本,因此本质上是无类型的,所以不,你不能这样做。
C preprocessor MACROS manipulate text, so are essentially typeless, so NO you can't do that.
您可以将另一个符号与其关联:
您只需手动保持它们一致即可。
请注意,这是一个危险的宏;您应该使用
typedef
来代替。对于宏:x
是一个指针,但y
不是。You could associate another symbol with it:
You just need to keep them consistent manually.
Note that that's a dangerous macro; you should use a
typedef
instead. With the macro:x
is a pointer, buty
isn't.您可以通过定义另一个宏和类型并使用
#ifdef
等来获得类似的效果。例如:...然后稍后...
这不完全相同,但它仍然可以让您到达那里。
You can get a similar effect by defining another macro along with the type, and using
#ifdef
etc. with that other macro. For example:...then later...
It's not quite the same thing, but it still gets you there.
不容易。你可以这样做:
但是你真的应该尽量减少预处理器对棘手事情的使用(除了简单变量之外的任何事情)。
有了枚举常量和内联函数,现在就不再需要这样的用途了。
Not easily. You could do something like:
But you really should be trying to minimise your use of the preprocessor for tricky things (anything other than simple variables).
With enumerated constants and inline functions, there's little need for such uses nowadays.
如果您只使用基本类型(因为它们只是字符串 - 请参阅米奇的答案),它会起作用。但是一旦您尝试使用指针,它就不再起作用 - 星号会引发预处理器循环:
但是如果您想根据不同类型做不同的事情,我将不得不建议切换到C++ 并使用 模板 和 模板专业化。很不情愿,因为模板语法非常丑陋,但你应该能够做任何你想做的事情。
希望有帮助!
It would work if you just used basic types (since they're just strings - see Mitch's answer). But as soon as you try to use pointers, it won't work any more - the asterisk throws the preprocessor for a loop:
But if you want do do different things based on different types, I'm going to have to recommend switching to C++ and using templates and template specialization. Reluctantly, since template syntax is incredibly ugly, but you should be able to do whatever you want.
Hope that helps!