Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define both operator void* and operator bool

I tried creating a class with one operator bool and one operator void*, but the compiler says they are ambigous. Is there some way I can explain to the compiler what operator to use or can I not have them both?

class A {
public:
    operator void*(){
        cout << "operator void* is called" << endl;
        return 0;
    }

    operator bool(){
        cout << "operator bool is called" << endl;
        return true;
    }
};

int main()
{
    A a1, a2;
    if (a1 == a2){
        cout << "hello";
    }
} 
like image 964
default Avatar asked Nov 28 '10 01:11

default


2 Answers

The problem here is that you're defining operator bool but from the sounds of it what you want is operator ==. Alternatively, you can explicitly cast to void * like this:

if ((void *)a1 == (void *)a2) {
    // ...
}

... but that's really bizarre. Don't do that. Instead, define your operator == like this inside class A:

bool operator==(const A& other) const {
    return /* whatever */;
}
like image 144
Michael Melanson Avatar answered Sep 21 '22 01:09

Michael Melanson


You could call the operator directly.

int main()
{
    A a1, a2;
    if (static_cast<bool>(a1) == static_cast<bool>(a2)){
        cout << "hello";
    }
} 

In this case, though, it looks like you should define operator==() and not depend on conversions.

like image 27
Lou Franco Avatar answered Sep 24 '22 01:09

Lou Franco