简体   繁体   English

使用 C++ 尾随返回类型时 auto 的含义是什么?

[英]What is the meaning of auto when using C++ trailing return type?

Instead of usual代替平常

void foo (void ) {
    cout << "Meaning of life: " << 42 << endl;
}

C++11 allows is an alternative, using the Trailing Return C++11允许使用尾随返回

auto bar (void) -> void {
    cout << "More meaning: " << 43 << endl;
}

In the latter - what is auto designed to represent?在后者中 - auto设计代表什么?

Another example, consider function另一个例子,考虑函数

auto func (int i) -> int (*)[10] {

}

Same question, what is the meaning of auto in this example?同样的问题,这个例子中auto是什么意思?

In general, the new keyword auto in C++11 indicates that the type of the expression (in this case the return type of a function) should be inferred from the result of the expression, in this case, what occurs after the -> .一般来说,C++11 中的 new 关键字auto表示应该从表达式的结果中推断出表达式的类型(在这种情况下是函数的返回类型),在这种情况下, -> .

Without it, the function would have no type (thus not being a function), and the compiler would end up confused.没有它,函数将没有类型(因此不是函数),编译器最终会感到困惑。

Consider the code:考虑代码:

template<typename T1, typename T2>
Tx Add(T1 t1, T2 t2)
{
    return t1+t2;
}

Here the return type depends on expression t1+t2 , which in turn depends on how Add is called.这里的返回类型取决于表达式t1+t2 ,而表达式又取决于Add的调用方式。 If you call it as:如果你称之为:

Add(1, 1.4);

T1 would be int , and T2 would be double . T1将是intT2将是double The resulting type is now double (int+double).结果类型现在是double (int+double)。 And hence Tx should (must) be specified using auto and ->因此应该(必须)使用auto->指定Tx

 template<typename T1, typename T2>
    auto Add(T1 t1, T2 t2) -> decltype(t1+t2)
    {
        return t1+t2;
    }

You can read about it in my article .你可以在我的文章中阅读它。

I think the answer is relatively straightforward, and not covered in other answers here.我认为答案相对简单,这里的其他答案没有涵盖。

Basically, without the auto , there are ambiguities, so The Committee decided "you need auto here to avoid those ambiguities".基本上,没有auto ,就会有歧义,所以委员会决定“你需要在这里使用auto以避免这些歧义”。

class A {
    T B;
};

class B;

A* f();

f()->B;

Now, what does f()->B mean?现在, f()->B是什么意思? Is it a function with no parameters that returns a B (with trailing return type syntax), or is it a function call to A* f() ?它是一个没有参数的函数返回一个B (带有尾随返回类型语法),还是一个对A* f()的函数调用?

If we didn't have the auto required at the start of the trailing return type syntax, we wouldn't be able to tell.如果在尾随返回类型语法的开头没有auto要求,我们将无法分辨。 With the auto , it's clear that this is a function call.使用auto ,很明显这是一个函数调用。

So, to avoid the unclearness here, we simply require auto at the start of any function declaration that uses a trailing return type.所以,为了避免这里的不清楚,我们只需要在任何使用尾随返回类型的函数声明的开始处使用auto

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM