disable assign integer to string c++

241 Views Asked by At

std::string (std::basic_string) have assignment operator for 'char' type. But, for this reason, std::string may assign any integral types. See little example.

#include <string>
enum MyEnum{ Va = 0, Vb = 2, Vc = 4 };

int main(){
       std::string s;
       s = 'a'; // (1) OK - logical.
       s = Vc; //  (2) Ops. Compiled without any warnings.
       s = true; //  (3) Ops....
       s = 23;    // (4) Ops...
 }

Q: How disable (or add warning ) (2, 3, 4) situations ??

There is a related Question

1

There are 1 best solutions below

0
Luis Machuca On

Given the constraints of C++03 and GCC 4.8 as in the tags, I could not get -Wconversion to do anything useful (and in GCC 7 it doesn't even generate the warnings for me despite telling it that I'm using --std=c++03).

As such, there's a good practical solution that requires only minimal change at your calling site:

Proxy the assignment via a class object that wraps your string and that allows assignment from char but disallows it from int:

#include <string>
enum MyEnum{ Va = 0, Vb = 2, Vc = 4 };

struct string_wr {
    string_wr (std::string& s) : val(s) {}
    operator std::string& () const { return val; }
    // we explicitly allow assigning chars.
    string_wr& operator= (char) { return *this; }

    // ww explicitly disable assigning ints by making the operator unreachable.
    private:
    string_wr& operator= (int);

    private:
    std::string& val;
};


int main(){
       std::string s;
       s = 'a'; // (1) OK - logical.
       s = Vc; //  (2) Ops. Compiled without any warnings.
       s = true; //  (3) Ops....
       s = 23;    // (4) Ops...

       string_wr m(s); // this is the only real change at the calling site
       m = 'a'; // (1) OK - logical.
       m = Vc; //  (2) Should fail with "assignment is private" kind of error.
       m = true; //  (3) Should fail...
       m = 23;    // (4) Should fail...

 }

However, if your final goal is to specifically get warnings or errors when using std::string, your best option in C++03 is to patch the <string> header to add the private int-assignment operator shown in the class above. But that means patching a system header and the procedure and results will be dependant on your compiler version (and will have to be repeated in each installation and compiler version).