0

How can I pass my object to an if statement and check if it is true or false

example:

struct A {
   int num;

   operator bool good() const {return num > 0;}
}

A a{1}; if(a) { /* it's all good man! */ }

I got inspired by std::function where you can pass it into a if statement and it will return true if function pointer is set:

void checkFunc( std::function<void()> const &func )
{
    // Use operator bool to determine if callable target is available.
    if( func )  
    {
        std::cout << "Function is not empty! Calling function.\n";
        func();
    }
    else
    {
        std::cout << "Function is empty. Nothing to do.\n";
    }
}
DEKKER
  • 877
  • 6
  • 19
  • This is called *conversion to bool*. Or you might have heard about *conversion operator*. Search these terms and you'll find plenty of related SO posts. This is also covered in any beginner level [c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jason Aug 25 '22 at 07:16
  • Aha... I had no idea what it is called – DEKKER Aug 25 '22 at 07:17
  • what is a little puzzling is that you are mentioning operator overloading in the title, but then there is no operator overloading, and the answer to the question is ... operator overloading. – 463035818_is_not_an_ai Aug 25 '22 at 07:18
  • see here: https://stackoverflow.com/a/16615725/4117728. Not sure if it is mentioned there, but note that `if` is a context where so called "contextual conversion to bool" takes place, ie the conversion operator can be `explicit` and will nevertheless be implicitly used when you write `if(func)` – 463035818_is_not_an_ai Aug 25 '22 at 07:21
  • @463035818_is_not_a_number yes I was a bit clumsy with this question. I updated question – DEKKER Aug 25 '22 at 07:23

0 Answers0