Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abusing the comma operator

I'm looking for an easy way to build an array of strings at compile time. For a test, I put together a class named Strings that has the following members:

Strings(); 
Strings(const Strings& that);
Strings(const char* s1);
Strings& operator=(const char* s1);
Strings& operator,(const char* s2);

Using this, I can successfully compile code like this:

Strings s;
s="Hello","World!";

The s="Hello" part invokes the operator= which returns a Strings& and then the operator, get called for "World!".

What I can't get to work (in MSVC, haven't tried any other compilers yet) is

Strings s="Hello","World!";

I'd assume here that Strings s="Hello" would call the copy constructor and then everything would behave the same as the first example. But I get the error: error C2059: syntax error : 'string'

However, this works fine:

Strings s="Hello"; 

So I know that the copy constructor does at least work for one string. Any ideas? I'd really like to have the second method work just to make the code a little cleaner.

like image 473
miked Avatar asked Oct 12 '09 22:10

miked


1 Answers

I think that the comma in your second example is not the comma operator but rather the grammar element for multiple variable declarations.

e.g., the same way that you can write:

int a=3, b=4

It seems to me that you are essentially writing:

Strings s="Hello", stringliteral

So the compiler expects the item after the comma to be the name of a variable, and instead it sees a string literal and announces an error. In other words, the constructor is applied to "Hello", but the comma afterwards is not the comma operator of Strings.

By the way, the constructor is not really a copy constructor. It creates a Strings object from a literal string parameter... The term copy constructor is typically applied to the same type.

like image 178
Uri Avatar answered Oct 20 '22 22:10

Uri