日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++11系列學習之類型推導_C 語言

作者:小杰編程 ? 更新時間: 2022-06-23 編程語言

auto類型推導

C++舊標準:

具有自動存儲的局部變量

auto int i = 0 //C++98

實際上我們一般不這樣寫,因為非static變量默認就是具有自動存儲的局部變量

C++11:

讓編譯器自動推斷出這個變量的類型,而不需要顯式指定類型

auto基本用法

演示:

auto x = 5 //x --> int
auto pi = new auto(1) //pi --> int*
const auto *v = &x, u = 6 //v --> const int* 、 u --> const int
static auto y = 0.0 //y --> double
int x = 0
auto * a = &x //a --> int* , auto為int
auto b = &x //b --> int* , auto 為 int*
auto c = x //c --> int& , auto為int
auto d = c //d --> int , auto為int
const auto e = x //e --> const int
auto f = e //f --> int
const auto& g = x //g --> const int&
auto& h = g //h --> const int&

上面就是通常會出現的所有情況,其實可以類比模板參數自動推導

auto 不能用于函數參數

auto 推導規則

黃金法則

  • 當不聲明為指針或引用時,auto的推到結果和初始化表達式拋棄引用和cv限定符(cosnt 和 volatile,下同)后類型一致
  • 當聲明為指針或引用時,auto的推到結果將保持初始化表達式的cv屬性

auto 的限制

  • 不能用于函數參數
  • 不支持非靜態成員變量的初始化
  • main函數中auto不會被推導為數組類型,而是指針類型

auto 適用場景

場景一:for循環中用來遍歷容器

for(auto it = resultMap.begin(); it != resultMap.end(); ++i){
//do something
}

場景二:用于不知道如何定義變量,多與泛型有關

class Foo{
public:
static int get(void)
{
return 0;
}
};
class Bar{
public:
static const char* get(void)
{
return "0";
}
};
template<class A>
void func(void)
{
auto val = A::get();
// ...
}

decltype 類型推導

decltype( exp )

exp 表示一個表達式
從格式上來看,decltype像sizeof ,但其用來在編譯時推導出一個表達式的類型

decltype 基本用法

int x = 0
decltype(x) y = 1 //y -> int
decltype(x + y) z = 0 //z -> int
const int& i = x
decltype(i) j = y //j -> const int &
cosnt decltype(z) *p = &z //*p -> const int, p -> const int *
decltype(z) * pi = &z //*pi -> int , pi -> int*
decltype(pi) * pp = &pi //*pp -> int * ,pp -> int **

decltype和&結合的推導結果,與引用折疊規則有關,將在本系列后續中詳細講解

decltype 推導規則

黃金法則:

  • exp是標識符、類訪問表達式,decltype(exp) 和exp的類型一致
  • exp是寒素調用,decltype(exp) 和返回值 的類型一致
  • 其他情況,若exp是個左值,則 ecltype(exp) 是exp類型的左值引用,否則和exp類型一致

decltype 適用場景

decltype適用于泛型相關

場景一:

標準庫中有些類型的定義

typedef decltype(nullptr) nullptr_t
typedef decltype(sizeof(0)) size_t
`

場景二:

通過變量表達式抽取變量類型實現簡寫

vector<int> v;
decltype(v):value_type i = 0

場景三:

template<class ContainerT>
class Foo
{
decltype(ContainerT().begin()) it_;
public:
void func(ContarinerT& container)
{
it_ = container.begin();
}
// ...
}

auto 和 decltype結合——返回類型后置

即通過兩個結合起來,使得語法更加靈活便捷

int & foo(int& i);
float foo(float& f)
template<typename T>
auto fun(T& val) -> decltype(foo(val))
{
return foo(val);
}

小結

autodecltype的出現不僅彌補了C++舊版標準的不足,也大大解放了開發人員的生產力,提升了效率。但是我們在使用的時候仍然需要注意,不能濫用,否則會出現我們期望得到的類型和最終程序的類型不一致,導致一些意想不到的BUG,給我維護增加了成本,適用和巧用才是正解

原文鏈接:https://blog.51cto.com/u_14156525/5235378

欄目分類
最近更新