What is 'operator auto' in C++?

Viewed 5080

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?

3 Answers

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
};

What is operator auto in C++?

operator auto() { return 0; }

operator T is a conversion operator to the type T. auto is a keyword for a placeholder type that will be deduced. When used as the return type, the type will be deducted from the return statement.

In this case, auto will be deduced to be int and thus it is an implicit conversion operator to int. It allows you to write for example:

A a;
int i = a;

in what language standard (e.g. C++17) did it appear?

Conversion operators have been in the language since at least the first standard version. auto return type was introduced in C++14.


a.operator auto();

Compilers seem to disagree how the operator could be called explicitly:

a.operator auto(); // Clang: OK,    GCC: ERROR
a.operator int();  // Clang: ERROR, GCC: OK

This may be under-specified in the language.

I don't think there's ever a reason to do such a call as you can use static_cast instead, so I would recommend avoiding it. Or if you prefer to use the call syntax, then don't use auto.

It's standard, from C++14, as you can see here.

In short, it means that the return type is determined, via type deduction, based on the return statement.

In other words, the three autos in the following snippet trigger the same type deduction mechanism

struct A
{
  auto operator()() { return 0; } // auto is the return type
  auto some_fun() { return 0; }   // auto is the return type
  operator auto() { return 0; }   // auto is not the return type
                                  // but it's deduced in the same way
};

Therefore, all requirements/limitations that you'd expect for other functions with auto return type also apply here, e.g. if more than one return statement is present, they should result in the same type being deduced, and so on.

Related