Alf P. Steinbach
unread,Mar 31, 2016, 6:50:11 PM3/31/16You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to
On 31.03.2016 20:44, Stefan Ram wrote:
>
> I observed that with GCC 5.1.1 and »-std=c++17«, I can write
> »if( s )« even though operator bool is explicit in »eta«.
`explicit` operator `bool` is implicitly invoked for an expression
that's used where the syntax requires a (C++ grammar) /condition/.
So, it's not perfect, but it's backward-compatible.
If you really want a conversion to `bool` that can only be explicitly
invoked, then the easiest is to use a named operation, e.g. `is_good`.
Alternatively, one can use a Rube Goldberg scheme with `operator
Private_member_ptr`, which doesn't convert to `void*`, so doesn't foul
up overload resolution in general, but which does convert to `bool`.
<code>
#include <iostream>
using namespace std;
class S
{
private:
enum Private {};
using Private_memptr = void(S::*)(Private);
void True( Private ) {}
public:
auto is_good() const -> bool { return true; }
operator Private_memptr() const
{ return (is_good()? &S::True : nullptr); }
};
void foo( void const* ) { cout << "foo(ptr)" << endl; }
void foo( ... ) { cout << "foo(...)" << endl; }
auto main()
-> int
{
S const o;
foo( o ); // Invokes "foo(...)".
if( o ) { cout << "Condition worked!" << endl; }
bool const b = o; // Converts even if this isn't a "condition".
(void) b;
#ifdef GAH
int const x = o; // !Doesn't convert.
(void) x;
#endif
}
</code>
I prefer the named operation explicitly invoked, rather than the
implicitly invoked conversion.
Cheers & hth.,
- Alf