箭头操作符( - >) [英] arrow operator (->) in function heading
问题描述
我发现这样的代码:
template <typename T, typename T1> auto compose(T a, T1 b) -> decltype(a + b) {
return a+b;
}
我想到了所有的细节,
告诉我,在哪里可以看到,箭头运算符( - >
)是什么意思在函数标题?
我认为纯逻辑上, - >
运算符确定一个类型,将由 auto
,但我想得到这个,但是找不到信息。
I figured with all details, that were new to me, but one.
Tell me please, where can I read about, what does the arrow operator (->
) mean in function heading?
I guess purely logically, that ->
operator determines a type, that will be gotten by auto
, but I want to get this straight, but can't find information.
推荐答案
在C ++ 11中,函数声明的语法:
In C++11, there are two syntaxes for function declaration:
return-type (
参数声明... )
return-type identifier (
argument-declarations... )
和
auto
(
argument-declarations ... )
- & code> 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 later? 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);
,编译器会告诉你它不知道 code>和
b
位于 decltype
参数中。这是因为它们只是由参数列表声明。
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.
这篇关于箭头操作符( - >)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!