C++ operator==(char, std::string)



  • In a recent project, I wrote a "bool operator==(char, std::string)". The implementation is as follows: (If CS screws this up, I'm not fighting it)

    bool operator==(char c, const string& s){
        if(s.length()==1 && s[0]==c) return true;
        else return false;
    }

    Is my implementing of the operator a WTF? Are there any possible "interesting" side-effects of this?



  • PMG! You idiot!!!!!

    bool operator==(char c, const string& s)
    {
        return (s.length()==1 && s[0]==c);
    }

     

     



  •  Why not just do if (s.length()==1 && s[0]==c) when you need it, instead of overloading an operator?



  • Doesn't really seem necessary to use operator overloading here as the implementation seems pretty trivial (and specialized to a specific domain? Why do you need to compare against the first character of a string and nothing else?).

     P.S. I fucking hate C++ and everything it stands for. Not to criticize your use of it specifically, though.



  •  

    @Dudehole said:

    Why do you need to compare against the first character of a string and nothing else?
     

    Only if the string is length 1. So essentially, it's a cross-datatype operator for 'z' =="z", which is normally not possible without casting, afaik.

    It also bugs out, I believe, when you do "z" == 'z', because char does not have a length() method, and 'z'[0] == "z"fill fail in the same way this overload was supposed to prevent.

    I've never coded a line of C or C++ in my life, so please tell me, am I right? 



  • @dhromed said:

    I've never coded a line of C or C++ in my life, so please tell me, am I right?

    No.

    @dhromed said:

    it's a cross-datatype operator for 'z' =="z"

    For 'z' == std::string("z").

    @dhromed said:

    which is normally not possible without casting

    It's not really possible with casting as well, unless you want to compare the integer values of the character and the pointer to the string literal.

    @dhromed said:

    It also bugs out, I believe, when you do "z" == 'z', because char does not have a length() method

    Nope, it bugs out because there's no suitable operator == (const char *, char). And you can't define that anyway, because you can't define operators on built-in types.

    @dhromed said:

    'z'[0] == "z" will fail in the same way this overload was supposed to prevent

    No, it will fail because you can't index chars. ;=]

    Cheers, HTH.



  • @Spectre said:

    No.
     

    Drat.

    @Spectre said:

    Cheers, HTH.

     Thx. Beer?


Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.