假设我们有一个具有以下接口的对象:
struct Node_t {
... const std::vector< something >& getChilds() const;
} node;
auto现在,我使用如下变量访问该属性:
auto childs = node->getChilds();
是什么类型的childs?一个std::vector< something >或一个参考?
的类型childs将是std::vector<something>。
auto由与模板类型推导相同的规则提供支持。template <typename T> f(T t);此处选择的类型与在调用中选择的类型相同,例如f(node->getChilds()).
类似地,auto&会让你得到被 挑选的相同类型template <typename T> f(T& t);,并且auto&&会让你得到被挑选的相同类型template <typename T> f(T&& t);。
这同样适用于所有其他组合,例如auto const&or auto*。
这是一个std::vector<something>. 如果你想要一个参考,你可以这样做:
auto & childs = node->getChilds();
那当然是一个常量引用。
auto给你std::vector<something>。您可以指定引用限定符auto &,或者,您可以使用decltype:
decltype( node->getChilds() ) childs = node->getChilds();