frans
frans

Reputation: 9778

Can I use different argument separators for macros than comma?

Is there a way to write a C++ macro with arguments which are not separated by a comma but any other character or even a space?

Example: I was just thinking about a lightweight way to have typed and named parameter to replace a call like this:

foo("value", (int)0);

with something like

foo(ARG(string key = "some_key"), 
    ARG(int value = 0));

which could be pre-processed to

foo(static_cast<string>("some_key"), static_cast<int>(0));

Of course this would be possible with using commas but I'm just curious..

Upvotes: 0

Views: 1011

Answers (2)

You cannot use the C / C++ preprocessor for that.

But you could generate your C++ code with another preprocessor, such as GNU m4 or GPP.

And you can also write your own, ad-hoc, C++ code emitter.

Upvotes: 1

Vittorio Romeo
Vittorio Romeo

Reputation: 93324

Is there a way to write a C++ macro with arguments which are not separated by a comma but any other character or even a space?

No, the preprocessor specification does not provide any way of changing the separator character.


I was just thinking about a lightweight way to have typed and named parameter to replace a call like this:

foo(ARG(string key = "some_key"), 
    ARG(int value = 0));

That can be implemented with templates overloading operator=. Louis Dionne showed a possible example implementation at this year's Meeting C++ keynote: you can find it here.

The final syntax looks like:

int main() {
  create_window("x"_arg = 20, "y"_arg = 50,
                "width"_arg = 100, "height"_arg = 5);
}

Other implementations with different syntax are possible - the point is that you do not need the preprocessor for this.

A production-ready example is the Boost Parameter Library.

Upvotes: 4

Related Questions