What is the purpose of `operator auto() = delete` in C++?

  c++, conversion-operator, language-lawyer

A class in C++ can define one or several conversion operators. Some of them can be with auto-deduction of resulting type: operator auto. And all compilers allow the programmer to mark any operator as deleted, and operator auto as well. For concrete type the deletion means that an attempt to call such conversion will result in compilation error. But what could be the purpose of operator auto() = delete?

Consider an example:

struct A {
    operator auto() = delete;
};

struct B : A { 
    operator auto() { return 1; }
};

int main() {
    B b;
    A a = b;   // error in Clang
    int i = b; // error in Clang and GCC
    int j = a; // error in Clang and GCC and MSVC
}

Since the compiler is unable to deduce the resulting type, it actually prohibits any conversion from this class or from derived classes with the error:

function 'operator auto' with deduced return type cannot be used before it is defined.

Demo: https://gcc.godbolt.org/z/zz77M5zsx

Side note that compilers slightly diverge in what conversions are still allowed (e.g. GCC and MSVC permit the conversion to base class), which one of them is right here?

Source: Windows Questions C++

LEAVE A COMMENT