且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++和预处理器宏:可变参数类型

更新时间:2023-12-01 09:35:10

如果您不介意调用语法略有不同,则可以使用boost.preprocessor:

If you don't mind a slightly different call syntax, you can use boost.preprocessor for that:

#include "boost/preprocessor.hpp"

// or to not include entire preprocessor header, the following header files will do
// #include <boost/preprocessor/stringize.hpp>
// #include <boost/preprocessor/seq/for_each.hpp>

#define CREATE_ONE_VAR(maR_, maData_, maVarName) \
  double maVarName {smc::define_variable (data, maVarName, BOOST_PP_STRINGIZE(maVarName))};

#define CREATE_VAR(maSeq) \
  BOOST_PP_SEQ_FOR_EACH(CREATE_ONE_VAR, %%, maSeq)

使用示例:

CREATE_VAR((x1)(x2)(x3))  //does the same as your original _CREATE_VAR3(x1, x2, x3)

现在您可以使用从1到 BOOST_PP_LIMIT_SEQ 的任意数量的变量来调用它,通常为256.

Now you can call it with any number of variables from 1 to BOOST_PP_LIMIT_SEQ, which is normally 256.

一些注意事项:我使用 %% 表示该参数未使用.您可以在其中放置任何内容(将其传递给内部宏的 maData 参数,我们不使用它).

A few notes: I use %% to indicate that the argument is unused. You can put anything in there (it gets passed to the internal macro's maData parameter, which we don't use).

您不应为宏命名,而以下划线和大写字母开头.根据标准,这是非法的,因为此类符号(以及包括两个连续下划线的任何符号)都保留给编译器使用.

You should not name your macros to start with an underscore followed by a capital letter. It's illegal according to the standard, as such symbols (as well as any symbol including two consecutive underscores) are reserved for your compiler.