overloading non-member conversion to bool operator

c++, operator-overloading

Solution

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

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();
}

then use it as:

if (to_bool(whatever)) 
{
}

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.

Problem

I am trying to write bool-conversion operator for std::bitset I tried: ``` template<size_t size> operator bool(std::bitset<size> & b) { return b.any(); } ``` but I got ``` error C2801: 'mynamespace::operator bool' must be a non-static member ``` from my visual-studio. But when I look up C2801 explanation it says nothing about conversion operators (only about =, ->, [],()) So, is it possible to somehow write "Conversion std::bitset to bool operator?" (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; ``` so the ideal syntax will be like: ``` Bitset b = whatewer; if(b) doStuff(); ``` ) If this overloading is not possible, what is the recommended workaround? so far I use it like: ``` if(b == Bitset(0)) doStuff(); ``` but I dont like it. Thank you

Original source