我正在尝试为 std::bitset 编写 bool 转换运算符
我试过:
template<size_t size>
operator bool(std::bitset<size> & b)
{
return b.any();
}
但是我得到了
error C2801: 'mynamespace::operator bool' must be a non-static member
来 self 的 Visual Studio 。
但是当我查找C2801 explanation它对转换运算符只字未提(仅涉及 =、->、[]、())
那么,是否有可能以某种方式编写“Conversion std::bitset to bool operator?”
(我不能在我的 if 语句中调用 b.any()
,因为当 std::bitset 被替换为 unsigned 或其他东西时必须运行相同的代码
typedef std::bitset<x> Bitset;
//typedef unsigned Bitset;
所以理想的语法应该是这样的:
Bitset b = whatewer;
if(b)
doStuff();
)
如果无法重载,建议的解决方法是什么?
到目前为止我使用它是这样的:
if(b == Bitset(0))
doStuff();
但我不喜欢。
谢谢
最佳答案
如错误消息所述,转换运算符必须是类的非静态 成员。没错。
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.
如果这是你的问题,那么你可以使用函数重载,并调用它传递将返回一个 bool 值的参数:
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<N>
然后将调用第二个重载函数,否则将调用第一个重载函数。
关于c++ - 将非成员转换重载到 bool 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9913834/