c++ - 将非成员转换重载到 bool 运算符

标签 c++ operator-overloading

我正在尝试为 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/

相关文章:

c++ - 显式类型转换与使用类型规则

c++ - 关于 vector 元素的弹出

c++ - "no matching function"在自定义类型上使用push_back时调用错误

java - 重绘的多参数版本如何在 Java 中工作?

c++ - 在可变参数模板中使用声明

c++ - 重载运算符<<

c++ - 使用宿主 C++ 应用程序编译 Lua 源代码

c++ - 需要 map 方面的帮助(C++、STL)

c++ - 为 DiagonalMatrix 对象重载 operator()

c++ - operator[] 重载以接受 char * 作为下标