本文介绍了auto和decltype之间的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是
c> rvalue 或 / code>。
,
#include< vector>
int main()
{
const std :: vector< int> v(1);
auto a = v [0]; // a has type int
decltype(v [0])b = 1; // b有类型const int&,
的返回类型// std :: vector< int> :: operator [](size_type)const
auto c = 0; // c有类型int
auto d = c; // d有类型int
decltype(c)e; // e有类型int,由c
命名的实体的类型decltype((c))f = c; // f has type int&,因为(c)是一个左值
decltype(0)g; // g有类型int,因为0是一个右值
}
重要的差异。注意 decltype(c)和 decltype((c))不一样!
且有时自动和 decltype 一起合作方式,例如在以下示例中(取自,并修改了一些):
int& foo(int& i);
float foo(float& f);
template< class T>
auto f(T& t) - > decltype(foo(t))
{
return foo(t);
}
维基百科进一步如下:
const int& foo();
int i
struct A {double x; };
const A * a = new A();
decltype(foo())x1; // type is const int&&
decltype(i)x2; // type is int
decltype(a-> x)x3; // type is double
decltype((a-> x))x4; // type is const double&
Is
auto x = initializer;equivalent to
decltype(initializer) x = initializer;or
decltype((initializer)) x = initializer;or neither?
解决方案decltype also considers whether the expression is rvalue or lvalue .
#include <vector> int main() { const std::vector<int> v(1); auto a = v[0]; // a has type int decltype(v[0]) b = 1; // b has type const int&, the return type of // std::vector<int>::operator[](size_type) const auto c = 0; // c has type int auto d = c; // d has type int decltype(c) e; // e has type int, the type of the entity named by c decltype((c)) f = c; // f has type int&, because (c) is an lvalue decltype(0) g; // g has type int, because 0 is an rvalue }That pretty much explains the imporant difference. Notice decltype(c) and decltype((c)) are not same!
And sometime auto and decltype works together in a cooperative way, such as in the following example (taken from wiki, and modified a bit):
int& foo(int& i); float foo(float& f); template <class T> auto f(T& t) −> decltype(foo(t)) { return foo(t); }Wikipedia further explains the semantics of decltype as follows:
const int&& foo(); int i; struct A { double x; }; const A* a = new A(); decltype(foo()) x1; // type is const int&& decltype(i) x2; // type is int decltype(a->x) x3; // type is double decltype((a->x)) x4; // type is const double&
这篇关于auto和decltype之间的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!