optional使用
代码一:
#include <iostream>
#include <boost/optional.hpp>
using namespace boost;
int main() {
optional<int> op;
op = 1000;
std::cout << "op=" << op << std::endl; //输出op=1
if (op.is_initialized()) {
std::cout << "op=" << op.get() << std::endl; //输出op=1000
}
return 0;
}
代码二:
#include <iostream>
#include <boost/optional.hpp>
using namespace boost;
int main() {
optional<int> op;
std::cout << "op=" << op << std::endl; //输出op=0
if (op.is_initialized()) {
std::cout << "op=" << op.get() << std::endl; //进不来
}
return 0;
}
从上面代码可知:直接使用op是可以拿到结果的,这是因为optional内部实现一个本类型到bool的隐式转换 ;所以得到的结果只有true 和 false。
// implicit conversion to "bool"
// No-throw
operator unspecified_bool_type() const { return this->safe_bool() ; }
// This is provided for those compilers which don't like the conversion to bool
// on some contexts.
bool operator!() const { return !this->is_initialized() ; }
使用get()函数是获取optional变量的值。如果在get()之前没有初始化且没有判断is_initialized(),会抛出异常。
reference_const_type get() const { BOOST_ASSERT(this->is_initialized()) ; return this->get_impl(); }
reference_type get() { BOOST_ASSERT(this->is_initialized()) ; return this->get_impl(); }
所以正确的使用方式应该是先去判断optional初始化,然后使用。
if (op.is_initialized()) {
std::cout << "op=" << op.get() << std::endl;
}
参考资料:
boost optional 源码:
https://www.boost.org/doc/libs/1_34_0/boost/optional/optional.hpp
C++ typedef的详细用法:
https://www.cnblogs.com/phpandmysql/p/10816949.html
unspecified_bool_type boost实现本类型到bool隐式转换:
https://blog.csdn.net/iteye_14736/article/details/81339891
operator bool()的作用及用法:
https://blog.csdn.net/znzxc/article/details/80385995