【问题标题】:C preprocessor directive to conditionally compile method calls with square brackets用于有条件地编译带方括号的方法调用的 C 预处理器指令
【发布时间】:2014-10-07 21:00:52
【问题描述】:

我知道我可以使用预处理器宏来有条件地编译某些方法调用,例如:

#if SOMETHING
#define fmod(...)
#endif
...
fmod(34.0, 452.0); //this line doesn't get compiled if SOMETHING != 0.

我可以使用相同的过程来有条件地编译带有左括号和右括号的方法调用吗?

假设我想有条件地编译对类MyClass的所有调用:

[MyClass doSomething];
[MyClass doSomethingElse];

#define MyClass[...] 产生:

[ doSomething];

这是一个错误。有什么想法吗?

【问题讨论】:

  • 看起来像XY problem?你想通过有条件地编译发送到MyClass的消息来完成什么?
  • 看,XY 问题在 Stackoverflow 上是受欢迎的,因为它们是 "practical, answerable questions based on actual problems that you face",除了它们在智力上很有价值。此外,这不是 XY 问题,因为我的问题有条件地编译发送到 MyClass 的消息。
  • 仅供参考,C++ 和 C 都不支持方括号表示法。您使用哪种语言编写?
  • 语言是Objective-C。

标签: objective-c c-preprocessor preprocessor-directive


【解决方案1】:

这是一种解决方法,依赖于在nil 上调用方法是没有操作的事实

@interface MyClassImpl : NSObject

+ (void)doSomething;

@end

#if SOMETHING
#define MyClass MyClassImpl
#else
#define MyClass ((Class)Nil)
#endif

【讨论】:

  • 不错的尝试,但这不起作用,因为您无法在构建时向nil 发送消息。您的代码编译为[Nil doSomething];,我得到一个构建错误:Bad receiver type 'void *'
  • @Eric 我不知道为什么Nil 的类型是void * 而不是Class,但你能试试更新的答案吗?否则你可以有Class globalNilClass = Nil; #define MyClass globalNilClass
【解决方案2】:

用宏重载方括号不会有任何运气,但您可以充实宏以使用不同的语法获得所需的效果。有条件地定义一个带有参数的宏。在一种情况下,宏将仅解析为参数,在另一种情况下,宏将解析为空白。

(编辑为使用可变参数宏)

#define COMPILE_CONDITIONAL

#if defined(COMPILE_CONDITIONAL)
  #define conditional(...) __VA_ARGS__
#else
  #define conditional(...) 
#endif

那么您的用例将如下所示:

conditional(fmod(34.0, 452.0));

conditional(MyClass doSomething);
conditional(MyClass doSomethingElse);

您最终可能会使用比“条件”更短的宏,在每一行输入都会很快变旧。

【讨论】:

  • 我在尝试您的代码时收到 Use of undeclared identifier 'x' 错误。
  • 您需要将其设为可变参数宏以允许在宏内包含,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多