[英]Meaning of “const -> std::string const&” after the function definition?
Reading the answer for one exercise in C++ Primer, 5th Edition , I found this code: 在C ++ Primer,第5版中阅读一个练习的答案,我找到了这段代码:
#ifndef CP5_ex7_04_h
#define CP5_ex7_04_h
#include <string>
class Person {
std::string name;
std::string address;
public:
auto get_name() const -> std::string const& { return name; }
auto get_addr() const -> std::string const& { return address; }
};
#endif
What does 是什么
const -> std::string const&
mean in this case? 这个意思是什么意思?
auto get_name() const -> std::string const& { return name; }
auto get_name() const -> std::string const& { return name; }
is trailing return type notation for the equivalent auto get_name() const -> std::string const& { return name; }
是等效的尾随返回类型表示法
std::string const& get_name() const { return name; }
Note that the equivalence is exact in the sense that you can declare a function using one syntax and define it with the other. 请注意,在使用一种语法声明函数并使用另一种语法定义函数的意义上,等价是精确的。
(This has been part of the C++ standard since and including C++11). (这是C ++标准的一部分,包括C ++ 11)。
The part -> std::string const&
is trailing return type and is new syntax since C++11. part
-> std::string const&
是尾随返回类型,是自C ++ 11以来的新语法。
The first const
says it a const
member function. 第一个
const
表示它是一个const
成员函数。 It can be safely called on a const
object of type Person
. 可以在
Person
类型的const
对象上安全地调用它。
The second part simply tells what the return type is - std:string const&
. 第二部分简单地告诉返回类型是什么 -
std:string const&
。
It is useful when the return type needs to be deduced from a template argument. 当需要从模板参数推导出返回类型时,它很有用。 For known return types, it is no more useful than than using:
对于已知的返回类型,它不比使用更有用:
std::string const& get_name() const { return name; }
It all makes more sense when you see an example where it actually matters; 当你看到一个真正重要的例子时,这一切都更有意义; as written in the question, it's just an alternative way to declare the return type.
如问题中所写,它只是声明返回类型的另一种方式。
If you have a template function where you can not know the return type in advance, this can actually help. 如果您有一个模板功能,您无法提前知道返回类型,这实际上可以提供帮助。 For example:
例如:
template <class X, class Y> auto DoSomeThing(X x, Y y) -> decltype(x * y);
You don't know what types X
and Y
actually are but you know the return value will have the same type as x * y
which can be deduced in this way. 你不知道
X
和Y
实际上是什么类型,但你知道返回值与x * y
类型相同,可以用这种方式推导出来。
const
is a cv-qualifier of the usual kind for the member function : *this
is const
inside the function. const
是成员函数的常用类型的cv限定符 : *this
是const
内部的const
。
-> std::string const&
pairs with auto
to form a trailing return type (see (2)). -> std::string const&
pairs with auto
形成尾随返回类型 (参见(2))。 The difference is only syntactic here -- the following syntax is equivalent: 区别仅在于语法 - 以下语法是等效的:
std::string const& get_name() const { return name; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.