什么是“ - >”函数声明后? [英] What is "->" after function declaration?

查看:177
本文介绍了什么是“ - >”函数声明后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个系统头文件中,我看到这样的表达式:

In one system header file, I see the expression like this:

auto create_task(_Ty _Param) -> task<typename details::_TaskTypeFromParam<_Ty>::_Type>
{...}



我不知道 - >它不是指针表达式或lambda表达式,任何人都可以帮助我?

I don't know what "->" means, it isn't pointer expression or lambda expression, can anyone help me?

推荐答案

这是C ++的新函数声明语法11,它被称为尾部返回类型。在函数声明结束时, - > 表示以下是函数的返回类型。它只能在使用 auto 关键字而不是通常预期的实际返回类型时使用。

It's the new function declaration syntax from C++11, and it's called the "trailing return type". At the end of a function declaration, -> means that the following is the return type of the function. It can only be used when the auto keyword is used instead of an actual return type where you would normally expect it.

例如,这两个声明是兼容的:

For instance, these two declarations are compatible:

int foo();
auto foo() -> int;

根据你的口味,你会发现它比旧的声明语法更漂亮,特别是当返回类型是非常长/复杂的:

Depending on your tastes, you may find it prettier than the old declaration syntax, especially when the return type is extremely long/complex:

task<typename details::_TaskTypeFromParam<_Ty>::_Type> create_task(_Ty _Param);
auto create_task(_Ty _Param) -> task<typename details::_TaskTypeFromParam<_Ty>::_Type>;

但是有时候可能需要使用模板,当函数的返回类型可以随参数

But sometimes it can be necessary with templates, when the return type of the function could vary with the arguments.

假设您希望模板函数添加变量:

Say you want a templated function to add variables:

template<typename T>
T add(const T& x, const T& y)
{
    return x + y;
}

这很棒,但你只能添加同一个变量类型。假设你想要添加任何类型的变量(如 add((int)1,(double)2))。

That's great, but you'll only be able to add variables of the same type. Suppose you would like to be able to add variables of any type (like add((int)1, (double)2)).

template<typename T, typename U>
??? add(const T& x, const U& y)
{
    return x + y;
}

问题是你不能预先告诉结果类型 x + y 将会。作为模板,它们甚至可以是非整数类型。 (你不能够 add(std :: string(x),y)?)

The problem is that you can't tell in advance what the result type of x + y will be. As templates stand, they could even be non-integral types. (Wouldn't you like to be able to do add(std::string("x"), "y")?)

Decltype 以及新的函数声明语法,可以解决这个问题。

Decltype, along with the new function declaration syntax, lets you solve this problem.

template<typename T, typename U>
auto add(const T& x, const U& y) -> decltype(x + y)
{
    return x + y;
}

Decltype 表达式的类型。由于您需要 x y 已声明 decltype(x + y)工作,您需要新的语法。

Decltype "returns" the type of an expression. Since you need x and y to have been declared for decltype(x + y) to work, you need the new syntax.

这篇关于什么是“ - &gt;”函数声明后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆