简体   繁体   中英

C++: how to return object's set state when used as logical value

I have some class that can be set or not:

Class obj;

I want its value, when used in logic, to return whether or not it's set:

if ( obj )
    obj.Clear();

if ( !obj )
    obj.Set( "foo" );

I thought of adding in an implicit conversion to bool, but I wonder if int would be necessary or whether there's a better way to go about this.

You can define a bool operator, as follows

#include <iostream>

struct Object{
    bool state;
    explicit operator bool()const{
        return state;
    }
};
int main(){

    Object o1;
    Object o2;
    o1.state = false;
    o2.state = true;
    std::cout << "\no1 state is " << (o1?  "true": "false");
    std::cout << "\no2 state is " << (!o2?  "false": "true");
}

The output is

o1 state is false
o2 state is true

Live

You can use std::optional or std::shared_ptr .

Example 1:

std::optional<Object> obj = Object();

if (obj) obj->useIt();

obj.reset();

if (obj) ... ;

Example 2

std::shared_ptr<Object> obj = new Object();

if (obj) obj->useIt();

obj.reset();

if (obj) ... ;

You should represent optional values using std::optional . This is self documenting, other programmers know what they are about, and you avoid checking for invariant states of your own class (reduce complexity). It also uses STL conventions for value wrappers (same as iterators, smart pointers, etc.).

If you don't want to or simply can't use it, look at it's implementation and follow the same rules:

  1. implement a bool-conversion-operator (explicit)
  2. provide a method (like std::optional::has_value() ) for use in templated methods

Note that if (...) performs an explicit bool-cast on the statement. So generally there is no need for implicit conversions. In order to avoid trouble using overloads, you should always go for explicit conversion-operators.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM