mercredi 11 mars 2015

Best way to deal with a trailing comma when using X macros in C++

What's the best way to deal with extra trailing commas when working with X macros? Specifically, I have the following setup in a file test01.cpp



struct Foo {
#define X(name,val) int name;
#include "test01.def"
#undef X

Foo() :
#define X(name,val) name(val),
#include "test01.def"
#undef X
{}
};

int main(){
Foo foo;
}


In test01.def, I have



X(foo,1)
X(bar,23)


This doesn't compile because of the error



test01.cpp: In constructor 'Foo::Foo()':
test01.cpp:10:5: error: expected identifier before '{' token
{}


Basically, there's a trailing comma after the last element in the member initializer list. Now, we can fix this by adding a dummy variable:



struct Foo {
private:
void * end;
public:
#define X(name,val) int name;
#include "test01.def"
#undef X

Foo() :
#define X(name,val) name(val),
#include "test01.def"
#undef X
end(nullptr)
{}
};

int main(){
Foo foo;
}


However, this is sort of ugly. As such, is there a better way to handle the trailing comma in the member initializer list?


Aucun commentaire:

Enregistrer un commentaire