升压转换::可选为bool [英] Conversion of boost::optional to bool
本文介绍了升压转换::可选为bool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何prevent这个code的最后一行进行编译?
How I can prevent the last line of this code from compiling?
#include <boost/optional.hpp>
int main()
{
typedef boost::optional<int> int_opt;
int_opt opt = 0;
bool x = opt; // <- I do not want this to compile
}
最后一行不检查选择
的包含int值,而是编译如下类型转换为bool,并且似乎没有什么用户意。
The last line doesn't examine opt
's contained int value, but instead compiles as a type conversion to bool, and doesn't seem to be what the user intended.
在安全布尔成语似乎是与此有关?
The safe bool idiom seems to be relevant here?
推荐答案
的boost ::可选的
的全部要点是使code这样的:
The whole point of boost::optional
is to enable code like this:
void func(boost::optional<int> optionalArg)
{
if (optionalArg) {
doSomething(*optionalArg);
}
}
所以隐式转换为布尔
是一个功能,而不是应该从编制pvented $ P $。
So the implicit conversion to bool
is a feature, and should not be prevented from compiling.
这篇关于升压转换::可选为bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文