C++中類型推斷(auto和decltype)的使用
類型推斷 是指在編程語(yǔ)言中自動(dòng)推導(dǎo)表達(dá)式的數(shù)據(jù)類型。在C++11之前,每個(gè)數(shù)據(jù)類型都需要在編譯時(shí)顯示聲明,在運(yùn)行時(shí)限制表達(dá)式的值,但在C++的新版本之后,引入了 auto 和 decltype等關(guān)鍵字,這允許程序員將類型推導(dǎo)留給了編譯器本身。
有了類型推斷功能,我們必須耗費(fèi)時(shí)間去寫編譯器已經(jīng)知道的東西。由于所有類型僅在編譯器階段推導(dǎo),因此編譯時(shí)間略有增加,但不會(huì)影響程序的運(yùn)行時(shí)間。
1. C++中的auto
C++中的 auto 關(guān)鍵字指定要聲明的變量的類型根據(jù)其初始值自動(dòng)推導(dǎo)。如果函數(shù)的返回類型是auto,那么它將在運(yùn)行時(shí)由返回類型表達(dá)式確定類型。auto的良好用途是在為容器創(chuàng)建迭代器時(shí)避免冗長(zhǎng)的初始化。
注意:使用auto關(guān)鍵字聲明的變量應(yīng)僅在聲明時(shí)初始化,否則將出現(xiàn)編譯時(shí)錯(cuò)誤。
C++中auto例子
// C++ program to demonstrate working of auto
// and type inference
#include <bits/stdc++.h>
using namespace std;
int main()
{
// auto a; this line will give error
// because 'a' is not initialized at
// the time of declaration
// a=33;
// see here x ,y,ptr are
// initialised at the time of
// declaration hence there is
// no error in them
auto x = 4;
auto y = 3.37;
auto z = 3.37f;
auto c = 'a';
auto ptr = &x;
auto pptr = &ptr; //pointer to a pointer
cout << typeid(x).name() << endl
<< typeid(y).name() << endl
<< typeid(z).name() << endl
<< typeid(c).name() << endl
<< typeid(ptr).name() << endl
<< typeid(pptr).name() << endl;
return 0;
}
輸出
i
d
f
c
Pi
PPi
注意:我們使用了 typeid 來(lái)獲取變量的類型。
這里,typeid是一個(gè)運(yùn)算符,用于獲取需要對(duì)象的動(dòng)態(tài)類型。
typeid(x).name() 返回 x 的數(shù)據(jù)類型,例如,它返回:
i表整數(shù)integer,d表 doublesf表 float,c表charPi表指向整數(shù)的指針Pd表示指向double的指針Pc表示指向 char 的指針PPi表示指向整數(shù)的指針的指針- 單指針前綴
P, - 雙指針用
PP作為前綴,以此類推
但實(shí)際返回的名稱主要取決于編譯器。
注意:auto的良好用途是在為容器創(chuàng)建迭代器時(shí)避免冗長(zhǎng)的初始化。
C++ auto關(guān)鍵字例子
// C++ program to demonstrate that we can use auto to
// save time when creating iterators
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Create a set of strings
set<string> st;
st.insert({ "geeks", "for", "geeks", "org" });
// 'it' evaluates to iterator to set of string
// type automatically
for (auto it = st.begin(); it != st.end(); it++)
cout << *it << " ";
return 0;
}
輸出
for geeks org
注意:如果給auto賦值一個(gè)整型引用,它也會(huì)變成整型。要使其成為引用類型,我們使用auto &。
- 返回整數(shù)引用類型的函數(shù):
int& fun() {}; m會(huì)默認(rèn)為 int類型而不是 int&類型:auto m = fun();n將是int&類型因?yàn)槭褂昧薬uto &:auto& n = fun();
2. C++中的decltype
在C++中,decltype關(guān)鍵字可以檢查實(shí)體聲明的類型或表達(dá)式的類型。‘auto’ 允許你聲明具有特定類型的變量,而decltype允許你從變量中提取類型,所以decltype是一種計(jì)算傳遞表達(dá)式類型的操作符。
下面解釋上述關(guān)鍵字及其用途:
例子
// C++ program to demonstrate use of decltype
#include <bits/stdc++.h>
using namespace std;
int fun1() { return 10; }
char fun2() { return 'g'; }
int main()
{
// Data type of x is same as return type of fun1()
// and type of y is same as return type of fun2()
decltype(fun1()) x;
decltype(fun2()) y;
cout << typeid(x).name() << endl;
cout << typeid(y).name() << endl;
return 0;
}
輸出
i
c
以下是演示decltype的使用的又一個(gè)示例,
// C++ program to demonstrate use of decltype
#include <bits/stdc++.h>
using namespace std;
// Driver Code
int main()
{
int x = 5;
// j will be of type int : data type of x
decltype(x) j = x + 5;
cout << typeid(j).name();
return 0;
}
輸出
i
示例:演示auto和decltype的使用的C++程序
下面是一個(gè)C++模板函數(shù)min_type(),它返回兩個(gè)數(shù)字中的最小值。這兩個(gè)數(shù)字可以是任何整數(shù)類型。返回類型是由兩者中的最小值來(lái)確定的。
// C++ program to demonstrate use of decltype in functions
#include <bits/stdc++.h>
using namespace std;
// A generic function which finds minimum of two values
// return type is type of variable which is minimum
template <class A, class B>
auto findMin(A a, B b) -> decltype(a < b ? a : b)
{
return (a < b) ? a : b;
}
// driver function to test various inference
int main()
{
// This call returns 3.44 of double type
cout << findMin(4, 3.44) << endl;
// This call returns 3 of double type
cout << findMin(5.4, 3) << endl;
return 0;
}
輸出:
3.44
3
decltype vs typeid
以下是decltype和typeid之間的一些主要區(qū)別
- decltype在編譯時(shí)提供類型信息,而typeid在運(yùn)行時(shí)提供。
- 因此,如果我們有一個(gè)基類引用(或指針)引用(或指向)一個(gè)派生類對(duì)象,decltype會(huì)將類型作為基類引用(或者指針),但typeid會(huì)將類型作為派生類引用(或者指針)。
到此這篇關(guān)于C++中類型推斷(auto和decltype)的使用的文章就介紹到這了,更多相關(guān)C++ 類型推斷 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++ CryptoPP使用AES實(shí)現(xiàn)加解密詳解
Crypto++ (CryptoPP) 是一個(gè)用于密碼學(xué)和加密的 C++ 庫(kù),提供了大量的密碼學(xué)算法和功能,這篇文章主要為大家介紹了C++ CryptoPP如何使用AES實(shí)現(xiàn)加解密,需要的可以參考下2023-11-11
C++關(guān)鍵字mutable學(xué)習(xí)筆記
這篇文章主要為大家介紹了C++關(guān)鍵字mutable學(xué)習(xí)筆記,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10
C++中動(dòng)態(tài)綁定和內(nèi)存管理的實(shí)現(xiàn)
本文主要介紹了C++中動(dòng)態(tài)綁定和內(nèi)存管理的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-12-12
C語(yǔ)言實(shí)現(xiàn)簡(jiǎn)單的停車場(chǎng)管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言實(shí)現(xiàn)簡(jiǎn)單的停車場(chǎng)管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
C++ OpenCV實(shí)戰(zhàn)之標(biāo)記點(diǎn)檢測(cè)的實(shí)現(xiàn)
這篇文章主要介紹了如何利用C++ OpenCV實(shí)現(xiàn)關(guān)鍵點(diǎn)的檢測(cè),文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)OpenCV有一定幫助,感興趣的小伙伴可以了解一下2022-03-03
C++實(shí)現(xiàn)LeetCode(80.有序數(shù)組中去除重復(fù)項(xiàng)之二)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(80.有序數(shù)組中去除重復(fù)項(xiàng)之二),本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07
OpenCV實(shí)現(xiàn)單目尺寸估計(jì)的案例詳解
這篇文章主要介紹了通過OpenCV如何實(shí)現(xiàn)單目尺寸估計(jì),文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)和工作有一定的參考價(jià)值,感興趣的可以了解一下2022-01-01
C++ std::make_unique和std::make_shared用法小結(jié)
本文主要介紹了C++ std::make_unique和std::make_shared用法,使用std::make_unique和std::make_shared能夠簡(jiǎn)化動(dòng)態(tài)分配內(nèi)存和構(gòu)造對(duì)象的過程,提高代碼的安全性和可讀性,感興趣的可以了解一下2023-11-11

