Abanoub
Abanoub

Reputation: 3809

error C2678: binary '!=' : no operator found which takes a left-hand operand

template<typename T> T SmartIO::Peek() {
    T temp;
    T tempReturn;

    while(true){
        temp = *(T*)&buffer[ptrSeek];

        if(temp !=0){
            ptrSeek++;
            tempReturn += *(T*)&buffer[ptrSeek];
        }
        else{
            break;
        }
    }

    return tempReturn;
}

so what i want to do is , start reading from ptrSeek start looping, adding the value to temp and check if temp's value !=0 add this value to tempReturn, and once the temp's value is 0 break the loop and return the tempReturnbut, but it's keep giving me this error :

error C2678: binary '!=' : no operator found which takes a left-hand operand of type 'std::basic_string<_Elem,_Traits,_Ax>' (or there is no acceptable conversion)

how can i solve this issue here?

Upvotes: 0

Views: 1725

Answers (2)

iammilind
iammilind

Reputation: 69988

You can specialize or overload the comparison part (here !=) for the types which are not directly comparable to 0. Just an example,

template<typename T>
bool NotEqualto0 (const T& obj) { return (obj != 0); }

// overload for std::string    
bool NotEqualto0 (const std::string &s) { return (s.c_str() != 0); }

...
if(NotEqualto0(temp))
...

[Above function is hardwired for 0; it can be generalized as per need.]

Upvotes: 0

templatetypedef
templatetypedef

Reputation: 372814

There is a fundamental issue with your template code if you are attempting to compare an arbitrary type T against the numeric constant 0, which you are doing in the code here:

T temp;

/* ... */

if(temp != 0){
     /* ... */
}

The problem here is that T is an arbitrary type (in this case, you seem to be instantiating the template with std::string), but you are expecting that type to be comparable to 0. This is perfectly fine - it just restricts T to be types that can be compared against 0 - but from the fact that you're reporting this as an error I'm not sure if you're aware of this.

Your options are either to not instantiate this template with std::string as an argument (the way it's written, I don't think you're supposed to be able to do this, since it looks like the function keeps adding values together of some type), or to debug the template and change its behavior. I'm not quite sure what you want the code to do, so in the latter case I'm not sure how I can assist.

Hope this clarifies things!

Upvotes: 4

Related Questions