将非成员转换重载到bool运算符 [英] overloading non-member conversion to bool operator

查看:167
本文介绍了将非成员转换重载到bool运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为std :: bitset编写bool转换运算符

I am trying to write bool-conversion operator for std::bitset

我试过:

template<size_t size>
operator bool(std::bitset<size> & b)
{
    return b.any();
}

但我有

error C2801: 'mynamespace::operator bool' must be a non-static member

从我的视觉工作室。

但是当我查找 C2801解释它没有说明转换运算符(只有=, - >,[],())

But when I look up C2801 explanation it says nothing about conversion operators (only about =, ->, [],())

所以,有可能以某种方式写转换std :: bitset到bool操作符?

So, is it possible to somehow write "Conversion std::bitset to bool operator?"

(我不能调用 b.any()在我的if语句中,因为同样的代码必须运行时std :: bitset替换为unsigned或某事

(I can not call b.any() in my if-statements, because the same code must run when std::bitset is replaced with unsigned or something

typedef std::bitset<x> Bitset;
//typedef unsigned Bitset;

所以理想的语法如下:

Bitset b = whatewer;
if(b)
    doStuff();

如果无法重载,建议的解决方法是什么?

If this overloading is not possible, what is the recommended workaround?

到目前为止我使用它:

if(b == Bitset(0))
    doStuff(); 

但我不喜欢。

谢谢

推荐答案

如错误讯息所示,转换运算子必须是非静态的类。

As the error message says, the conversion operator must be a non-static member of a class. That is true.


我不能在我的if语句中调用b.any(),因为同样的代码必须运行std: :bitset替换为unsigned或某事。

I can not call b.any() in my if-statements, because the same code must run when std::bitset is replaced with unsigned or something.

如果这是你的问题,那么你可以使用函数重载,参数,将返回一个布尔值:

If that is your problem, then you can use function overload, and call it passing the argument which will return a boolean value:

template<typename T>
bool to_bool(T const & b)
{
    return b; //implicit conversion (if allowed) for all other types
}

template<size_t N>
bool to_bool(std::bitset<N> const & b)
{
    return b.any();
}

然后使用它:

if (to_bool(whatever)) 
{
}

它会调用正确的重载。如果 whatever 的类型是 std :: bitset ,那么将调用第二个重载函数,否则第一个将被调用。

It will call the correct overload. If the type of whatever is std::bitset<N> then the second overloaded function will be called, or else the first one will be called.

这篇关于将非成员转换重载到bool运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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