Is there a way to undefine the += on strings and wstrings for chars and wchar_t?
Basically I want to avoid bugs like the following:
int age = 27; std::wstring str = std::wstring(L'User's age is: '); str += age; std::string str2 = std::string('User's age is: '); str2 += age;
The above code will add the ascii character 27 to the string instead of the number 27.
I obviously know how to fix this, but my question is: how do I produce a compiler error in this situation?
Note: You can override += on std::string and int to properly format the string, but this is not what I want to do. I want to completely disallow this operator on these operands.
You cannot deactivate a specific function of a class (here std::basic_string) as it is it’s interface that clearly (and officially) allow that manipulation. Trying to overload the operator will only mess things up.
Now, you can ‘wrap’ std::basic_string in another class, using private inheritance or composition and then use the public interface as a proxy to the std::basic_string part, but only the functions you want to be usable.
I recommand first replacing you string types with typedefs :
Then once your application compile fine after having replaced std::string and std::wstring by myapp::String and myapp::UTFString (those are example names), you define the wrapper class somewhere :
…then, you simply replace those lines :
… and your example will crash :
Here is the full test application code i wrote to prove that (compiled on vc9) :
I think it would cleanly resolve your problem, but you’ll have to wrapp all the functions.