c++visual-c++lambda

explicit operator bool not called inside lambda — MSVC bug?


#include <functional>

struct T {
    explicit operator bool() { return true; }
};

int main() {
    T t;

    if(t) {} // OK

    auto l = [&]() {
        if (t) {} // Error
    };
}

MSVC's behaviour seems oddly inconsistent here; the only difference between the OK line and the Error line is that one is in a lambda. Is this a bug?

Error message (version 17.00.51025 for x86):

error C2451: conditional expression of type 'T' is illegal
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called


Solution

  • Is this a bug?

    Yes, definitely. There is nothing wrong in your program, the bool conversion operator shall be invoked in both cases.