这个调用对象作为默认参数C ++

时间:2016-11-02 15:52:33

标签: c++ macros this

我正在尝试创建一个带有可变数量的参数(0到1)的C ++宏,它将充当函数调用的包装器,以便将调用对象的this指针作为默认参数值提供。

以便用户可以拨打电话:

    CALL(pointer) // An argument is supplied, pass it to the call
    CALL()        // No argument supplied, pass the this pointer value instead

1 个答案:

答案 0 :(得分:0)

您可以使用boost编写一个宏,该宏允许您计算有多少参数。但是,仅当您至少有一个参数时才有效。当你有零参数提升认为你有一个。所以这不是你问题的答案(除非你能够通过至少一个参数)。尽管如此,我仍然将其作为答案发布,因为它可能对具有类似情况的人有所帮助,而其他“重复”问题的接受答案并未提供此解决方案。

#include <iostream>
#include <boost/preprocessor/tuple/elem.hpp>

#define CALL(...)                                    \
  {                                                  \
    auto num = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__);  \
    std::cout << "called with " << num << " args." << std::endl; \
  }

int main() {
  CALL(1, 2);
  CALL(1);
}