Reputation: 2555
I can define a macros which print only fixed variable count, for example:
#define PRINT_PARAMS(param) std::cout << "test: " << std::string( #param ) << " = " << param << "\n";
// using:
int varI = 5;
PRINT_PARAMS( varI );
// output:
test: varI = 5
How to define a macros which will do something like that:
PRINT_PARAMS( varI1, strValue2, floatValue3, doubleValue4 );
// output:
varI1 = 5, strValue2 = some string, floatValue3 = 3.403f, ....
I mean any number of input parameters.
Upvotes: 0
Views: 171
Reputation: 37914
#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)
}
Upvotes: 2
Reputation: 4429
Don't have a compiler to hand but was wondering if the following variadic macro would work (or at least help give you an idea.)
#define PRINT_PARAMS(param) std::cout << "test: " << std::string( #param ) << " = " << param << "\n";
#define PRINT_PARAMS(a, ...) { PRINT_PARAMS((a)); PRINT_PARAMS(__VA_ARGS__); }
Upvotes: 2