mirror of
https://github.com/CnTransGroup/EffectiveModernCppChinese.git
synced 2025-02-05 16:51:05 +08:00
Update item3.md
This commit is contained in:
parent
4753623c99
commit
55885ba78a
@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
我们将从一个简单的情况开始,没有任何令人惊讶的情况。相比模板类型推导和`auto`类型推导(参见[Item1](https://github.com/kelthuzadx/EffectiveModernCppChinese/blob/master/1.DeducingTypes/item1.md)和[Item2](https://github.com/kelthuzadx/EffectiveModernCppChinese/blob/master/1.DeducingTypes/item2.md)),`decltype`只是简单的返回名字或者表达式的类型:
|
我们将从一个简单的情况开始,没有任何令人惊讶的情况。相比模板类型推导和`auto`类型推导(参见[Item1](https://github.com/kelthuzadx/EffectiveModernCppChinese/blob/master/1.DeducingTypes/item1.md)和[Item2](https://github.com/kelthuzadx/EffectiveModernCppChinese/blob/master/1.DeducingTypes/item2.md)),`decltype`只是简单的返回名字或者表达式的类型:
|
||||||
````cpp
|
````cpp
|
||||||
const int i=0; //decltype(i)是const int
|
const int i = 0; //decltype(i)是const int
|
||||||
|
|
||||||
bool f(const Widget& w); //decltype(w)是const Widget&
|
bool f(const Widget& w); //decltype(w)是const Widget&
|
||||||
//decltype(f)是bool(const Widget&)
|
//decltype(f)是bool(const Widget&)
|
||||||
@ -17,19 +17,19 @@ struct Point{
|
|||||||
|
|
||||||
Widget w; //decltype(w)是Widget
|
Widget w; //decltype(w)是Widget
|
||||||
|
|
||||||
if (f(w))... //decltype(f(w))是bool
|
if (f(w))… //decltype(f(w))是bool
|
||||||
|
|
||||||
template<typename T> //std::vector的简化版本
|
template<typename T> //std::vector的简化版本
|
||||||
class vector{
|
class vector{
|
||||||
public:
|
public:
|
||||||
...
|
…
|
||||||
T& operator[](std::size_t index);
|
T& operator[](std::size_t index);
|
||||||
...
|
…
|
||||||
}
|
};
|
||||||
|
|
||||||
vector<int> v; //decltype(v)是vector<int>
|
vector<int> v; //decltype(v)是vector<int>
|
||||||
...
|
…
|
||||||
if (v[0] == 0)... //decltype(v[0])是int&
|
if (v[0] == 0)… //decltype(v[0])是int&
|
||||||
````
|
````
|
||||||
看见了吧?没有任何奇怪的东西。
|
看见了吧?没有任何奇怪的东西。
|
||||||
|
|
||||||
@ -65,7 +65,7 @@ auto authAndAccess(Container& c, Index i) //不那么正确
|
|||||||
|
|
||||||
````cpp
|
````cpp
|
||||||
std::deque<int> d;
|
std::deque<int> d;
|
||||||
...
|
…
|
||||||
authAndAccess(d, 5) = 10; //认证用户,返回d[5],
|
authAndAccess(d, 5) = 10; //认证用户,返回d[5],
|
||||||
//然后把10赋值给它
|
//然后把10赋值给它
|
||||||
//无法通过编译器!
|
//无法通过编译器!
|
||||||
@ -159,13 +159,13 @@ int x = 0;
|
|||||||
decltype(auto) f1()
|
decltype(auto) f1()
|
||||||
{
|
{
|
||||||
int x = 0;
|
int x = 0;
|
||||||
...
|
…
|
||||||
return x; //decltype(x)是int,所以f1返回int
|
return x; //decltype(x)是int,所以f1返回int
|
||||||
}
|
}
|
||||||
|
|
||||||
decltype(auto) f2()
|
decltype(auto) f2()
|
||||||
{
|
{
|
||||||
int x =0l;
|
int x = 0;
|
||||||
return (x); //decltype((x))是int&,所以f2返回int&
|
return (x); //decltype((x))是int&,所以f2返回int&
|
||||||
}
|
}
|
||||||
````
|
````
|
||||||
|
Loading…
Reference in New Issue
Block a user