boost optional 以及 operator bool

boost 库有一个组件,叫做 optional,用来保存一些可有可无的成员变量,说明见这里,http://www.boost.org/doc/libs/…,样例用法如下

#include <boost/optional.hpp>
#include <stdio.h>
#include <string>

int main() {
    boost::optional<std::string> name;
    if (name) {
        printf("name is %s\n", name->c_str());
    } else {
        printf("no name\n");
    }
    return 0;
}

注意两个点,一个是这个是指针调用 c_str(),另外就是,一个对象本身可以放在 if 里面去 test,这个之前还没想过,查了资料,发现在实现上是这么来搞的:

#include <boost/optional.hpp>
#include <stdio.h>
#include <string>

class Object {
public:
    std::string name;
    operator bool() {
        if (name.empty()) {
            return false;
        } else {
            return true;
        }
    }
};

int main() {
    Object obj;
    if (obj) {
        printf("obj is %s\n", obj.name.c_str());
    } else {
        printf("no obj...\n");
        obj.name = "foo";
        if (obj) {
            printf("obj has name now %s\n", obj.name.c_str());
        } else {
            printf("still no obj\n");
        }
    }
    return 0;
}

以前只是知道 operator+ 之类的,都不知道 operator bool() 这种

Leave a Reply

Your email address will not be published. Required fields are marked *