boost :: boost转换为bool [英] Conversion of boost::optional to bool

查看:310
本文介绍了boost :: boost转换为bool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何防止此代码的最后一行编译?

  #include< boost / optional.hpp> 

int main()
{
typedef boost :: optional< int> int_opt;
int_opt opt = 0;
bool x = opt; //< - 我不想让这个编译
}

最后一行doesn 't检查 opt 的包含int值,而是编译为一个类型转换为bool,似乎不是用户的意图。

$

解决方案

安全的bool习语似乎与这里有关? code> boost :: optional 是启用这样的代码:

  void func boost :: optional< int> optionalArg)
{
if(optionalArg){
doSomething(* optionalArg);
}
}

所以隐式转换为 bool 是一个功能,不应该阻止编译。


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
}

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?

解决方案

The whole point of boost::optional is to enable code like this:

void func(boost::optional<int> optionalArg)
{
    if (optionalArg) {
       doSomething(*optionalArg);
    }
}

So the implicit conversion to bool is a feature, and should not be prevented from compiling.

这篇关于boost :: boost转换为bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆