函数标题中的箭头运算符 (->) [英] Arrow operator (->) in function heading

查看:26
本文介绍了函数标题中的箭头运算符 (->)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下代码:

template <typename T, typename T1> auto compose(T a, T1 b) -> decltype(a + b) {
   return a+b;
}

有一件事我无法理解:

在哪里可以找到函数标题中箭头运算符 (->) 的含义?

Where could I find out what the arrow operator (->) means in the function heading?

我猜纯粹从逻辑上讲,-> 运算符确定了一种类型,auto 将被推导出来,但我想弄清楚这一点.我找不到任何信息.

I guess purely logically, that the -> operator determines a type, that auto will be deduced to, but I want to get this straight. I can't find any information.

推荐答案

在C++11中,函数声明有两种语法:

In C++11, there are two syntaxes for function declaration:

   返回类型 标识符 ( 参数声明...)

    return-type identifier ( argument-declarations... )

   auto identifier ( argument-declarations... ) -> return_type

    auto identifier ( argument-declarations... ) -> return_type

它们是等价的.现在,当它们等效时,您为什么要使用后者?好吧,C++11 引入了这个很酷的 decltype 东西,它可以让你描述表达式的类型.因此,您可能希望从参数类型派生返回类型.所以你试试:

They are equivalent. Now when they are equivalent, why do you ever want to use the latter? Well, C++11 introduced this cool decltype thing that lets you describe type of an expression. So you might want to derive the return type from the argument types. So you try:

template <typename T1, typename T2>
decltype(a + b) compose(T1 a, T2 b);

并且编译器会告诉你它不知道 abdecltype 参数中是什么.那是因为它们仅由参数列表声明.

and the compiler will tell you that it does not know what a and b are in the decltype argument. That is because they are only declared by the argument list.

您可以通过使用 declval 和已声明的模板参数轻松解决该问题.喜欢:

You could easily work around the problem by using declval and the template parameters that are already declared. Like:

template <typename T1, typename T2>
decltype(std::declval<T1>() + std::declval<T2>())
compose(T1 a, T2 b);

除了现在变得非常冗长.所以替代声明语法被提出并实现,现在你可以写

except it's getting really verbose now. So the alternate declaration syntax was proposed and implemented and now you can write

template <typename T1, typename T2>
auto compose(T1 a, T2 b) -> decltype(a + b);

它不那么冗长,范围规则也不需要改变.

and it's less verbose and the scoping rules didn't need to change.

C++14 更新:C++14 也只允许

   auto identifier ( argument-declarations... )

    auto identifier ( argument-declarations... )

只要函数在使用前完全定义并且所有return语句都推导出相同的类型.如果您想隐藏源文件中的主体,-> 语法对于公共函数(在标题中声明)仍然很有用.显然,模板无法做到这一点,但有一些具体类型(通常通过模板元编程派生)很难以其他方式编写.

as long as the function is fully defined before use and all return statements deduce to the same type. The -> syntax remains useful for public functions (declared in the header) if you want to hide the body in the source file. Somewhat obviously that can't be done with templates, but there are some concrete types (usually derived via template metaprogramming) that are hard to write otherwise.

这篇关于函数标题中的箭头运算符 (->)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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