c++ - 在函数声明中使用 ->

标签 c++ c++11

<分区>

Possible Duplicate:
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;
};

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

最佳答案

What's the -> operator doing in there?

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

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的返回类型,那么你必须使用这种形式;尽管正如您所指出的那样,在许多情况下(包括这个)您根本不需要指定。

关于c++ - 在函数声明中使用 ->,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13158354/

相关文章:

c++ - CImg错误未处理的异常堆栈溢出

c++ - 使用 std::weak_ptr 共享资源所有权

c++ - Boost hana 获取字符串中的类型

c++ - "Can' t 解析构造函数"在类中使用类型别名时

c++ - echo 示例编译错误 :ambiguous call to overloaded function

c++ - 工厂方法反if实现

c++ - 从spinbox保存数据

c++ - 将函数模板定义为类模板的回调

C++,接受后无法接收数据和无效套接字

c++ - 可变参数模板参数的传递位置