Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading non-member conversion to bool operator

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

like image 918
relaxxx Avatar asked Mar 28 '12 18:03

relaxxx


2 Answers

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.

like image 127
Nawaz Avatar answered Sep 22 '22 02:09

Nawaz


§12.3.2/1: "A member function of a class X with a name of the form [...] specifies a conversion from X to the type specified..." (C++11 uses the same section number and nearly the same wording, adding only that the function takes no parameters).

The other possible way to define a conversion is a constructor (§12.3.1), which is obviously a class member as well.

In short, yes, conversions must always be defined as member functions.

One way to do what you want would be to write a wrapper around std::bitset that provides the conversion you care about:

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

But if you decide to do that, you'll need to write forwarding functions for essentially all the pieces of bitset you're using (ctors, assignment, etc.)

like image 27
Jerry Coffin Avatar answered Sep 24 '22 02:09

Jerry Coffin