I’m making my own string class and I’d like to ensure that CString a = "Hello " + "World!"; works (i.e. does not give a compiler error such as: cannot add 2 pointers).
My string class automatically converts to char* when needed and thus writing printf(a) would not break the code.
Is there any way to replace the compiler behavior around characters ? (i.e. between inverted commas, "abc"). Or, alternatively, to change the behavior of the + operator to handle strings?
The right answer
No.
You cannot overload operators for built-ins, such as pointers.
James McNellis already answered the question, so I won’t elaborate.
A possible alternative…
(I use std::string because I have no info on your in-house string)
Using a typedef will add some sugar to your syntax:
But then, I wouldn’t pollute the global namespace with a two-characters symbol just for a little sugar… And as far as I know, the code is inefficient (two string objects created, plus one temporary, without guarantee the compiler will optimize it all away…)
For curiosity’s sake…
As a curiosity, by wrapping the string into a thin class, you can “add” those two pointers.
First, let’s create the wrapper :
As you can see, it’s both inlined, and will do nothing… Still, it’s able to cast itself into a const char * pointer (this kind of hack is dangerous, so be sure it’s what you want to do).
Then, for this wrapper, let’s overload the addition operator :
And now, let’s write a
mainfunction using the wrapper, typedefed for ease of use :Which compiles and gives the following result :
Disclaimer: I just wanted to play with the idea your question gave me, and share it with you. Don’t apply this kind of code just because you can. Indeed, this code should be refined to cover all cases efficiently before even being used, and even then, a simple
typedef std::string S_ ;would be better IMHO.AFAIK, I wouldn’t use it because I’m happy with the current STL API.
And what about C++0x ?
In C++0x, you’ll be able to create your own literals. The code will be kinda like :
And you’ll use it so :
For more information, see the following SO question: What new capabilities do user-defined literals add to C++?.