简体   繁体   English

C++:当用作逻辑值时如何返回对象的集合 state

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

I have some class that can be set or not:我有一些可以设置或不设置的 class :

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.我想添加到 bool 的隐式转换,但我想知道是否需要 int 或者是否有更好的方法来 go 解决这个问题。

You can define a bool operator, as follows可以定义一个bool运算符,如下

#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 output 是

o1 state is false
o2 state is true

Live居住

You can use std::optional or std::shared_ptr .您可以使用std::optionalstd::shared_ptr

Example 1:示例 1:

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

if (obj) obj->useIt();

obj.reset();

if (obj) ... ;

Example 2示例 2

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

if (obj) obj->useIt();

obj.reset();

if (obj) ... ;

You should represent optional values using std::optional .您应该使用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).这是自我记录,其他程序员知道他们在做什么,并且您避免检查您自己的 class 的不变状态(降低复杂性)。 It also uses STL conventions for value wrappers (same as iterators, smart pointers, etc.).它还对值包装器使用 STL 约定(与迭代器、智能指针等相同)。

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提供用于模板化方法的方法(如std::optional::has_value()

Note that if (...) performs an explicit bool-cast on the statement.请注意, if (...)对语句执行显式布尔转换。 So generally there is no need for implicit conversions.所以通常不需要隐式转换。 In order to avoid trouble using overloads, you should always go for explicit conversion-operators.为了避免使用重载时出现问题,对于显式转换运算符,您应该始终使用 go。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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