c++ - bool vs void* casts on the same object -


the code below prints 'operator bool' when used in if statement , 'operator void*' when needs bool function call.

why isn't using operator bool function call too? , how make use in both cases?

#include <iostream>  class { public:     explicit operator bool() const     {         std::cout << "operator bool" << std::endl;         return true;     }      operator void*() const     {         std::cout << "operator void*" << std::endl;         return 0;     } };  void f(bool valid) {     std::cout << "f called " << valid << std::endl; }  int main(int argc, char *argv[]) {     a;      if(a)         std::cout << "if a" << std::endl;      f(a);      return 0; } 

in if statement, implicit , explicit conversion operators considered. because a has operator bool, chooses one, better match converting a void* , converting bool.

but in every other statement, not conditions (if, while, ...), explicit conversion operators not participate in overload resolution, , valid operator operator void*, can used because there implicit conversion pointers bool.

if want operator bool selected, need make non-explicit, or use cast (because that's marking explicit means, making sure 1 has explicit use it):

f(static_cast<bool>(a)); 

Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -