C++'operator auto'是什么?



Clang和Visual Studio编译器(但不是GCC(允许编写如下代码:

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

什么是operator auto?它是特定编译器的扩展还是标准语言功能?如果是,它出现在什么语言标准(例如C++17(中?

在用户定义的转换函数中使用auto时,将通过返回类型推导来推导类型,即这种情况下的int(0(。这是在C++14中引入的。

占位符auto可以在转换类型id中使用,指示推断返回类型:

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

C++中的运算符auto是什么?

operator auto() { return 0; }

operator T是类型T的转换运算符。auto是将要推导的占位符类型的关键字。当用作返回类型时,该类型将从返回语句中扣除。

在这种情况下,auto将被推导为int,因此它是int的隐式转换算子。它允许你写例如:

A a;
int i = a;

它出现在什么语言标准(例如C++17(中?

转换运算符至少从第一个标准版本开始就使用该语言。CCD_ 11返回类型是在C++14中引入的。


a.operator auto();

编译器似乎不同意如何显式调用运算符:

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

这可能在语言中规定不足。

我不认为有任何理由进行这样的调用,因为你可以使用static_cast,所以我建议避免使用它。或者,如果你更喜欢使用调用语法,那么就不要使用auto

它是标准的,来自C++14,正如您在这里看到的那样。

简而言之,这意味着返回类型是根据返回语句通过类型推导确定的。

换句话说,以下代码段中的三个auto触发了相同类型的推导机制

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

因此,对于auto返回类型的其他函数,您期望的所有要求/限制也适用于此,例如,如果存在多个返回语句,则它们应该导致推导出相同的类型,依此类推