安全bool成语和显式运算符bool之间的不兼容性 [英] Incompatibilities between safe bool idiom and explicit operator bool

查看:171
本文介绍了安全bool成语和显式运算符bool之间的不兼容性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在已经使用C ++ 11功能的代码中用显式运算符bool 替换所有的安全bool成语的实例(因此,较旧的编译器不认识显式转换操作符没关系),所以我想知道它是否会导致一些微妙的问题。



因此, c>显式运算符bool ?可能导致的不兼容性(即使是最微小的) p>

编辑:我知道切换是一个好主意,无论如何,后者是一个语言功能,由编译器很好理解,所以它的工作不会比什么事实上只是一个黑客。

解决方案

可能是最大的区别,假设你的代码没有错误(我知道,不是一个安全的假设),在某些情况下,你可能想要一个隐式转换到 bool 显式转换函数将不匹配。

  struct S1 $ b b {
operator S1 *(){return 0; } / *我知道,不是最好的类型* /
} s1;

struct S2
{
显式运算符bool(){return false; }
} s2;

void f()
{
bool b1 = s1; / * okay * /
bool b2 = s2; / * not okay * /
}


I'm thinking of replacing all the instances of safe bool idiom by explicit operator bool in code which already uses C++11 features (so the fact that older compilers don't recognized explicit conversion operators will not matter), so I'd like to know if it can cause some subtle problems.

Thus, what are all the possible incompatibilities (even the most minute ones) that can be caused by switching from old and dull safe bool idiom to new and shiny explicit operator bool?

EDIT: I know that switching is a good idea anyway, for the latter is a language feature, well-understood by the compiler, so it'll work no worse than what's in fact just a hack. I simply want to know the possible differences.

解决方案

Probably the biggest difference, assuming your code is free of bugs (I know, not a safe assumption), will be that in some cases, you may want an implicit conversion to exactly bool. An explicit conversion function will not match.

struct S1
{
    operator S1*() { return 0; } /* I know, not the best possible type */
} s1;

struct S2
{
    explicit operator bool() { return false; }
} s2;

void f()
{
    bool b1 = s1; /* okay */
    bool b2 = s2; /* not okay */
}

这篇关于安全bool成语和显式运算符bool之间的不兼容性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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