将非成员转换重载为bool运算符

rel*_*xxx 6 c++ operator-overloading

我正在尝试为std :: bitset编写bool转换运算符

我试过了:

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

但我明白了

error C2801: 'mynamespace::operator bool' must be a non-static member
Run Code Online (Sandbox Code Playgroud)

来自我的视觉工作室.

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

那么,有可能以某种方式写"将std :: bitset转换为bool运算符吗?"

(我不能b.any()在我的if语句中调用,因为当std :: bitset被unsigned或者某些东西替换时,必须运行相同的代码

typedef std::bitset<x> Bitset;
//typedef unsigned Bitset;
Run Code Online (Sandbox Code Playgroud)

所以理想的语法就像:

Bitset b = whatewer;
if(b)
    doStuff();
Run Code Online (Sandbox Code Playgroud)

)

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

到目前为止,我使用它像:

if(b == Bitset(0))
    doStuff(); 
Run Code Online (Sandbox Code Playgroud)

但我不喜欢它.

谢谢

Naw*_*waz 6

如错误消息所示,转换运算符必须是类的非静态成员.那是真实的.

我不能在我的if语句中调用b.any(),因为当std :: bitset被unsigned或其他东西替换时,必须运行相同的代码.

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

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();
}
Run Code Online (Sandbox Code Playgroud)

然后用它作为:

if (to_bool(whatever)) 
{
}
Run Code Online (Sandbox Code Playgroud)

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

  • @Nawaz非常感谢,这是最好的解决方法.我甚至可以称之为`if((to_bool)(what))`以获得更多的演员印象:)再次感谢你 (2认同)

Jer*_*fin 5

§12.3.2/ 1:" 具有[...]形式名称的类X的成员函数指定从X到指定类型的转换..."(C++ 11使用相同的节号和几乎相同的措辞,仅添加该函数不带参数).

定义转换的另一种可能方式是构造函数(第12.3.1节),它显然也是一个类成员.

简而言之,是的,转换必须始终定义为成员函数.

做你想做的事的一种方法是编写一个包装器std::bitset来提供你关心的转换:

template <int size>
class mybitest {
    std::bitset<size> bits;
public:
    operator bool() { return bits.any(); }
}
Run Code Online (Sandbox Code Playgroud)

但是如果你决定这样做,你需要为bitset你正在使用的所有部分(ctors,赋值等)编写转发函数.