mardi 2 février 2021

explicit conversion operator and const-reference qualification

The following example compiles fine on godbolt with -std=c++17 with clang, but fails with msvc and gcc:

struct Foo
{
};

struct Bar
{
    explicit operator Foo() // w/o explicit qualification all are happy
    {
        return Foo();
    }
};

int main()
{
    Bar b;
    const Foo& foo = static_cast<const Foo&>(b); // only clang happy with this
    const Foo& foo2 = static_cast<const Foo&>(static_cast<Foo>(b)); // clang / msvc / gcc happy with this
    return 0;
}

So as far as I understand the explicit on the operator simply prohibit implicit conversions, and since the page lists qualification conversions among them, I would assume clang is simply wrong in this case? Or am I missing something?

I'd ideally want to stick with the single cast, since I am using this in a templated code, where if the const-reference conversion operator is available it is used. But I could also drop the explicit constraint.

Aucun commentaire:

Enregistrer un commentaire