Search code examples
c++operator-keyword

What is 'operator auto' in C++?


Clang and Visual Studio compilers (but not GCC) allow one to write the code as follows:

struct A
{
  operator auto() { return 0; }
};

int main()
{
   A a;
   a.operator auto();
}

What is operator auto? Is it an extension of a particular compiler or a standard language feature and if yes in what language standard (e.g. C++17) did it appear?


Solution

  • When auto is used in user-defined conversion function the type will be deduced via return type deduction, i.e. int for this case (0). This was introduced in C++14.

    The placeholder auto can be used in conversion-type-id, indicating a deduced return type:

    struct X {
        operator int(); // OK
        operator auto() -> short;  // error: trailing return type not part of syntax
        operator auto() const { return 10; } // OK: deduced return type
    };