【问题标题】:Preprocessor Definition in function parameter函数参数中的预处理器定义
【发布时间】:2015-05-27 07:30:52
【问题描述】:

这是我第一次遇到这种类型的代码。我很难理解它。

#ifndef A
#define A
#endif

#ifndef B
#define B
#endif

void funct (structA* A paramA, structB* B paramB){};

参数中预处理器A和B的作用是什么?

【问题讨论】:

    标签: c++ c


    【解决方案1】:

    为:

    #define A this_is_a
    

    预处理器会将A 替换为this_is_a

    为:

    #define A
    

    预处理器会将A 替换为空。

    因此,在您的示例代码中,AB 符号将被丢弃。人们有时会使用这种技术来注释代码,例如:

    #define IN
    #define OUT
    

    现在您可以注释函数参数,显示它们是“输入”还是“输出”参数:

    void my_function(IN int i, OUT int& x) { ... }
    

    【讨论】:

      【解决方案2】:

      你可以这样做(假设你的代码在foo.h):

      非常量 A

      #include "foo.h"
      ...
      

      常量 A

      #define A const
      #include "foo.h"
      

      基本上,您的代码所做的是它允许向参数添加标志。如果包含标头时未定义A 宏,则将其定义为空字符串,因此将其忽略。但是,如果定义了宏,则将其值代入签名中。

      另一种用法是根据编译器功能选择功能。例如:

      #ifdef HAVE_CPP11
      # define FORWARD_REF &&
      # define FORWARD(T, x) std::forward<T>(x)
      #else
      # define FORWARD_REF const &
      # define FORWARD(T, x) x
      #endif
      
      template <typename T>
      void function_that_forwards_parameter(T FORWARD_REF t) {
          foo(FORWARD(T, t));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-12
        • 1970-01-01
        • 2010-11-18
        相关资源
        最近更新 更多