使用 - >在函数声明中

时间:2012-10-31 12:49:39

标签: c++ c++11

  

可能重复:
  What is “->” after function declaration?

我刚刚使用新的auto关键字遇到了以下C ++函数示例,我希望有人可以帮助我理解语法的含义。

template <class T, class U>
auto add(T t, U u) -> decltype(t + u);

auto f = [](int a, int b) -> int {
   return a*b;
};

具体来说,我对函数签名中->的用户感到困惑,我希望这些内容可以写成as

template <class T, class U>
auto add(T t, U u)
{
    decltype(t + u);
}

auto f = [](int a, int b){
    return a*b;
};

->运算符在那里做了什么,我在哪里可以了解有关此语法的更多信息?

6 个答案:

答案 0 :(得分:13)

  

->运营商在那里做什么?

这是尾随返回类型。而不是:

int f();

你可以等同地写:

auto f() -> int;

如果返回类型取决于函数参数类型,则需要使用此表单;这些参数在声明之后才可用:

decltype(t+u) add(T t, U u); // Error: uses `t` and `u` before they're declared
auto add(T t, U u) -> decltype(t + u); // OK

另外,如果要指定lambda的返回类型,则必须使用此表单;但是,正如你所指出的那样,在许多情况下(包括这一个)你根本不需要指定它。

答案 1 :(得分:3)

[dcl.spec.auto] / 2解释了如何使用自动返回类型编写函数声明:

  

在这样的声明符有效的任何上下文中,auto类型说明符可能带有带尾随返回类型(8.3.5)的函数声明符。

然后,在[dcl.fct] / 12中,有一个注释:

当函数的返回类型很复杂时,Typedef和trailing-return-types有时很方便。例如,上面的函数fpif可能已被声明为

typedef int IFUNC(int);
IFUNC* fpif(int);

auto fpif(int)->int(*)(int)

trailing-return-type对于在declarator-id之前指定更复杂的类型最有用:

template <class T, class U> auto add(T t, U u) -> decltype(t + u);

而不是

template <class T, class U> decltype((*(T*)0) + (*(U*)0)) add(T t, U u);

答案 2 :(得分:2)

此语法(所谓的 trailing-return-type )是将表达式用作返回类型的解决方法,如下所示:

template <class T, class U>
   decltype(t + u) add(T t, U u) { ... }

...在C ++中不正确。

不得不在Wiki中解释这个问题(我想)。

答案 3 :(得分:1)

->尾随返回类型

C ++ 11提出了另一种函数声明语法。 auto关键字取代了通常的函数返回类型,实际的返回类型取代->

例如,

auto f (int a, int b) -> int;

相当于

int f(int a, int b);

此功能对于必须从模板参数推导出返回类型的模板函数最有用。

例如,

template <class T, class U>
auto add(T t, U u) -> decltype(t + u);

返回类型将是表达式(t+u)的类型。

答案 4 :(得分:1)

  

什么是 - &gt;操作员在那里做,我在哪里可以了解更多   关于这个语法?

cprogramming对此有一个非常好的解释。

使用的本质 - &gt; (在你的情况下)或auto,decltype很方便,让你更专注于编程逻辑。

尾随返回类型( - &gt;)可帮助您在函数声明本身中包含返回类型信息。

如果是您的替代示例:

auto add(T t, U u)
{
    decltype(t + u);
}

如果函数相当复杂,那么对于程序的读者来说,找出预期的返回类型是非常困难的(不是很明显)。

答案 5 :(得分:0)

- &gt;函数声明中的operator指定返回“auto”的函数的返回类型。它在C ++ 11标准的第8章中定义。

相关问题