一个宏,用于打印变量名称及其值

时间:2016-05-07 22:05:36

标签: c++ macros

我可以定义一个只打印固定变量计数的宏,例如:

#define PRINT_PARAMS(param) std::cout << "test: " << std::string( #param ) << " = " << param << "\n";

// using:
int varI = 5;
PRINT_PARAMS( varI );

// output:
test: varI = 5

如何定义将执行类似操作的宏:

PRINT_PARAMS( varI1, strValue2, floatValue3, doubleValue4 );

// output:
varI1 = 5, strValue2 = some string, floatValue3 = 3.403f, ....

我的意思是任意数量的输入参数。

2 个答案:

答案 0 :(得分:3)

#include <string>
#include <iostream>

//"for each" macro iterations
#define FE_1(Y, X) Y(X) 
#define FE_2(Y, X, ...) Y(X)FE_1(Y, __VA_ARGS__)
#define FE_3(Y, X, ...) Y(X)FE_2(Y, __VA_ARGS__)
#define FE_4(Y, X, ...) Y(X)FE_3(Y, __VA_ARGS__)
#define FE_5(Y, X, ...) Y(X)FE_4(Y, __VA_ARGS__)
//... repeat as needed

//the "for each" call
#define GET_MACRO(_1,_2,_3,_4,_5,NAME,...) NAME 
#define FOR_EACH(action,...) \
  GET_MACRO(__VA_ARGS__,FE_5,FE_4,FE_3,FE_2,FE_1)(action,__VA_ARGS__)

//function to print a single
#define PRINT_SINGLE(param) std::cout << "test: " << std::string( #param ) << " = " << param << "\n";

//function to print n amount
#define PRINT_PARAMS(...) FOR_EACH(PRINT_SINGLE,__VA_ARGS__)

int main(){
  std::string s1 = "hello";
  float f = 3.14;
  int i = 42;
  PRINT_PARAMS(s1,f,i)

}

答案 1 :(得分:2)

没有可编程的编译器,但想知道以下可变参数宏是否可行(或者至少有助于给你一个想法。)

#define PRINT_PARAMS(param) std::cout << "test: " << std::string( #param ) << " = " << param << "\n";

#define PRINT_PARAMS(a, ...) { PRINT_PARAMS((a)); PRINT_PARAMS(__VA_ARGS__); }