C++安全布尔习语无法使用 Visual C++ 进行编译10(2010)
大家好,我从这个页面的 C++ safe bool idiom 类派生了我的类:The Safe Bool idiom作者:Bjorn Karlsson
class Element : public safe_bool<>
{
public:
bool Exists() const;
// boolean_test() is a safe_bool method
bool boolean_test() const { return Exists(); };
};
当我尝试在 if 表达式中使用它时,如下所示,
Element ele;
...
if(ele)
我收到错误 C2451:“Element”类型的条件表达式非法。如果我尝试将其转换为如下所示的 bool,则会收到此错误
Element ele;
...
if((bool)ele)
error C2440: 'typecast' :无法从 'Element' 转换为 'bool'
这是我第一次使用安全 bool习语,我不确定这是不允许的还是 Visual C++ 10 中的错误。有什么评论吗?提前致谢!
Hey guys, I have derived my class from the C++ safe bool idiom class from this page : The Safe Bool Idiom by Bjorn Karlsson
class Element : public safe_bool<>
{
public:
bool Exists() const;
// boolean_test() is a safe_bool method
bool boolean_test() const { return Exists(); };
};
When I tried to use it in the if expression like below
Element ele;
...
if(ele)
I got an error C2451: conditional expression of type 'Element' is illegal. If I try to cast it to bool like below, I got this error
Element ele;
...
if((bool)ele)
error C2440: 'type cast' : cannot convert from 'Element' to 'bool'
This is the 1st time I am using safe bool idiom, I am not sure if this is not allowed or a bug in Visual C++ 10. Any comments? Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
安全布尔习惯用法是允许的,尽管我通常这样写:
这就是我所看到的它的实现方式。事实上,Boost 以这种方式为智能指针类实现该习惯用法 (使用包含文件)。
The safe bool idiom is allowed, although I typically write it like this:
This how I've seen it implemented. In fact, Boost implements the idiom in this manner for the smart pointer classes (using an include file).
它似乎无法用任何编译器编译。显然,
safe_bool
无法返回其基类中受保护方法的地址。您应该向safe_bool_base
添加一个公共方法并返回该方法的地址。另外,似乎使用非依赖构造禁用了运算符
==
和!=
(即使未实例化也可能会导致错误)。也许这可以解决问题:
It doesn't seem to compile with any compiler. Apparently
safe_bool
cannot return the address of a protected method in its base. You should add a public method tosafe_bool_base
and return the address of that.Also, it seems that operators
==
and!=
are disabled using a non-dependent construct (may cause an error even if not instantiated).Perhaps this fixes things: