11

I get the Compiler Error C2071 when I try to implement the explicit operator bool:

class C
{
public:

    explicit operator bool() const
    {
        return !!*this;
    }
};

Why? How can I solve this problem?
I'm using Visual Studio 2012 RC.

Nick
  • 10,309
  • 21
  • 97
  • 201
  • 7
    As far as I know Visual Studio doesn't support this feature. I think you're stuck with the safe bool idiom^Whack. – R. Martinho Fernandes Jul 06 '12 at 15:24
  • 10
    weird way to do infinite loops... – PlasmaHH Jul 06 '12 at 15:27
  • 3
    In g++ 4.7, that produces [Stack Overflow](http://stackoverflow.com). – Robᵩ Jul 06 '12 at 15:28
  • have you meant `return !!this;`, by any chance? – Agent_L Jul 06 '12 at 15:30
  • 6
    @Agent_L that would be a weird way of saying `return true;`. I suspect the OP implemented it this way because `operator!` is already overloaded with the desired semantics, but just not included in the sample code. – R. Martinho Fernandes Jul 06 '12 at 15:30
  • @Agent_L: `this` is never null and there are no "null references". Sure, compilers will sometimes allow it to work, but you're always playing with Undefined Behavior. – aschepler Jul 06 '12 at 15:35
  • @aschepler, yeah, the docs say it's UB, however compilers define it very precisely. null thises and null refs do happen, and once you in the project amongst ducks, you quack like they do. – Agent_L Jul 06 '12 at 15:40
  • 3
    @Agent_L: No, compilers do *not* define those very precisely... or, actually, I guess they do. They define it as "screw you, go play with the explosives, I won't do shit to help you out". – Xeo Jul 06 '12 at 15:41
  • @Xeo you're certainly wiser than I am. Please, teach me about compilers that are unable to cope with 0 in ECX. Or on the stack. – Agent_L Jul 06 '12 at 15:49
  • 1
    @Xeo: haha, you were supposed to test it, not use. http://ideone.com/hgLHj – Agent_L Jul 06 '12 at 16:06
  • @PlasmaHH: Assuming `C::operator!()` returns `bool` (which is the norm), there's no infinite loop. – Marcelo Cantos Apr 21 '13 at 00:54
  • 1
    @MarceloCantos: I tried hard, but could not spot the operator! you are mentioning. – PlasmaHH Apr 21 '13 at 18:57

2 Answers2

11

Visual Studio 2012 does not support explicit conversion operators, see C++11 Features in Visual C++ 11.

These articles talk about the safe bool idiom:

gliderkite
  • 8,828
  • 6
  • 44
  • 80
  • In Visual Studio 2012 I have installed November CTP: http://aka.ms/vc-ctp This compiler upgrade pack was supposed to add (among other C++11 features) explicit conversion operator. But the syntax still doesn't work. Am I missing something? – prapin Dec 29 '12 at 21:36
2

If you look at a list of features in Visual Studio 2010 you can see that it was not an available feature. A look at What's New for Visual C++ in Visual Studio 2012 shows that is has not been added.

NominSim
  • 8,447
  • 3
  • 28
  • 38