最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C++17之std::any的具體使用

 更新時間:2022年02月07日 09:57:45   作者:云洞  
本文主要介紹了C++17之std::any的具體使用,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

    一般來說,c++是一種具有類型綁定和類型安全性的語言。值對象聲明為具有特定類型,該類型定義哪些操作是可能的以及它們的行為方式。值對象不能改變它們的類型。

    std: any是一種值類型,它能夠更改其類型,同時仍然具有類型安全性。也就是說,對象可以保存任意類型的值,但是它們知道當(dāng)前保存的值是哪種類型。在聲明此類型的對象時,不需要指定可能的類型。

    訣竅在于,對象同時擁有包含的值和使用typeid包含值的類型。因?yàn)檫@個值可以有任何大小,所以可以在堆上分配內(nèi)存,鼓勵實(shí)現(xiàn)避免小對象的動態(tài)分配。也就是說,如果分配一個字符串,對象將為該值分配內(nèi)存并復(fù)制該字符串,同時也在內(nèi)部存儲分配的字符串。稍后,可以執(zhí)行運(yùn)行時檢查來確定當(dāng)前值的類型,并使用any_cast<該值的類型>獲取值。

1. 使用std::any

下面的例子演示了std::any:

std::any a; // a is empty
std::any b = 4.3; // b has value 4.3 of type double
 
a = 42; // a has value 42 of type int
b = std::string{"hi"}; // b has value "hi" of type std::string
 
if (a.type() == typeid(std::string)) 
{
    std::string s = std::any_cast<std::string>(a);
    useString(s);
}
else if (a.type() == typeid(int)) 
{
    useInt(std::any_cast<int>(a));
}

    可以聲明std::any為空或由特定類型的值初始化。初始值的類型成為所包含值的類型。通過使用成員函數(shù)type(),可以根據(jù)任何類型的類型ID檢查所包含值的類型。如果對象是空的,對象類型ID是typeid(void)。要訪問包含的值,可以通過std::any_cast<對象類型>的方式:

auto s = std::any_cast<std::string>(a);

如果轉(zhuǎn)換失敗,因?yàn)閷ο鬄榭栈虬念愋筒黄ヅ?,則拋出std::bad_any_cast。因此,在不檢查或不知道類型的情況下,最好實(shí)現(xiàn)以下功能:

try {
auto s = std::any_cast<std::string>(a);
...
}
catch (std::bad_any_cast& e) {
std::cerr << "EXCEPTION: " << e.what() << '\n';
}

注意,std::any_cast<>創(chuàng)建了一個傳遞類型的對象。如果將std::string作為模板參數(shù)傳遞給std::any_cast<>,它將創(chuàng)建一個臨時string(一個prvalue),然后用它初始化新對象s。如果沒有這樣的初始化,通常最好轉(zhuǎn)換為引用類型,以避免創(chuàng)建臨時對象:

std::cout << std::any_cast<const std::string&>(a);

要修改該值,需要轉(zhuǎn)換為對應(yīng)的引用類型:

std::any_cast<std::string&>(a) = "world";

還可以為std::any對象的地址調(diào)用std::any_cast。在這種情況下,如果類型匹配,則強(qiáng)制轉(zhuǎn)換返回相應(yīng)的地址指針;如果不匹配,則返回nullptr:

auto p = std::any_cast<std::string>(&a);
if (p) {
...
}

例1:

#include <iostream>
#include <any>
 
int main()
{
    std::any i = 42;
    const auto ptr = std::any_cast<int>(&i);
    if (ptr)
    {
        std::cout << ptr << std::endl;
    }
 
    return 0;
}

結(jié)果如下:

要清空現(xiàn)有std::任何可以調(diào)用的對象:

方法1:a.reset(); // makes it empty

方法2:a = std::any{};

方法3: a = {};

可以直接檢查對象是否為空:

if (a.has_value()) {
...
}

還要注意,值是使用衰減類型存儲的(數(shù)組轉(zhuǎn)換為指針,忽略頂層引用和const)。對于字符串常量,這意味著值類型是const char*。要檢查type()并使用std::any_cast<>,必須使用以下類型:

std::any a = "hello"; // type() is const char*
if (a.type() == typeid(const char*)) { // true
...
}
if (a.type() == typeid(std::string)) { // false
...
}
std::cout << std::any_cast<const char*>(v[1]) << '\n'; // OK
std::cout << std::any_cast<std::string>(v[1]) << '\n'; // EXCEPTION

    std::any沒有定義比較運(yùn)算符(因此,不能比較或排序?qū)ο?,沒有定義hash函數(shù),也沒有定義value()成員函數(shù)。由于類型只在運(yùn)行時才知道,所以不能使用泛型lambdas處理與類型無關(guān)的當(dāng)前值??偸切枰\(yùn)行時函數(shù)std::any_cast<>來處理當(dāng)前值。

    然而,可以將std::任何對象放入容器中。

例2:

#include <iostream>
#include <vector>
#include <any>
 
int main()
{
    std::vector<std::any> v;
    v.push_back(42);
    std::string s = "hello";
    v.push_back(s);
    for (const auto& a : v) {
        if (a.type() == typeid(std::string)) {
            std::cout << "string: " << std::any_cast<const std::string&>(a) << '\n';
        }
        else if (a.type() == typeid(int)) {
            std::cout << "int: " << std::any_cast<int>(a) << '\n';
        }
    }
}

結(jié)果如下:

 2. std::any類型和操作

本節(jié)詳細(xì)描述std::any的類型和操作。

2.1 std::any的類型

在頭文件<any>中,c++標(biāo)準(zhǔn)庫定義了類std::any,如下所示:

namespace std {
class any;
}

也就是說,std::any根本不是類模板。

此外,定義了以下類型和對象:

如果類型轉(zhuǎn)換失敗,則拋出異常類型std::bad_any_cast,它派生自std::bad_cast,而std::bad_cast派生自std::exception。

any對象還可以使用<utility>中定義的對象std::in_place_type(類型為std::in_place_type_t)。

2.2 std::any操作

std::any操作

std::any操作
函數(shù)說明
constructors創(chuàng)建一個any對象(可能調(diào)用底層類型的構(gòu)造函數(shù))
make_any()創(chuàng)建一個any對象(傳遞值來初始化它)
destructor銷毀any對象
=分配一個新值
emplace<T>()分配一個類型為T的新值
reset()銷毀any對象的值(使對象為空)
has_value()返回對象是否具有值
type()返回當(dāng)前類型為std::type_info對象
any_cast<T>()使用當(dāng)前值作為類型T的值(如果其他類型除外)
swap()交換兩個any對象的值
  

1. 構(gòu)造函數(shù)

默認(rèn)情況下,std::any的初始值為空。

std::any a1; // a1 is empty

如果傳遞一個值進(jìn)行初始化,則將其衰減類型用作所包含值的類型:

std::any a2 = 42; // a2 contains value of type int
std::any a3 = "hello"; // a2 contains value of type const char*

要保存與初始值類型不同的類型,必須使用in_place_type標(biāo)記:

std::any a4{std::in_place_type<long>, 42};
std::any a5{std::in_place_type<std::string>, "hello"};

即使傳遞給in_place_type的類型也會衰減。下面的聲明包含一個const char*:

std::any a5b{std::in_place_type<const char[6]>, "hello"};

要通過多個參數(shù)初始化可選對象,必須創(chuàng)建該對象或?qū)td::in_place_type添加為第一個參數(shù)(不能推斷包含的類型):

std::any a6{std::complex{3.0, 4.0}};
std::any a7{std::in_place_type<std::complex<double>>, 3.0, 4.0};

甚至可以傳遞一個初始化器列表,后面跟著附加的參數(shù):

// initialize a std::any with a set with lambda as sorting criterion:
auto sc = [] (int x, int y) { return std::abs(x) < std::abs(y);};
 
std::any a8{std::in_place_type<std::set<int,decltype(sc)>>, {4, 8, -7, -2, 0, 5}, sc};

注意,還有一個方便的函數(shù)make_any<>(),它可以用于單個或多個參數(shù)(不需要in_place_type參數(shù))。必須顯式指定初始化的類型(如果只傳遞一個參數(shù),則不會推導(dǎo)出初始化的類型):

auto a10 = std::make_any<float>(3.0);
auto a11 = std::make_any<std::string>("hello");
auto a13 = std::make_any<std::complex<double>>(3.0, 4.0);
auto a14 = std::make_any<std::set<int,decltype(sc)>>({4, 8, -7, -2, 0, 5}, sc);

2. 訪問值

要訪問包含的值,必須使用std::any_cast<>將其轉(zhuǎn)換為其類型。將該值轉(zhuǎn)換為一個字符串,有幾個選項(xiàng):

std::any_cast<std::string>(a) // yield copy of the value
std::any_cast<std::string&>(a); // write value by reference
std::any_cast<const std::string&>(a); // read-access by reference

在這里,如果轉(zhuǎn)換失敗,將拋出std::bad_any_cast異常。

如果把std::any中所包含的類型轉(zhuǎn)換為移除了傳遞類型的頂層引用后的類型ID,則轉(zhuǎn)換類型是適合的。如下:

#include <iostream>
#include <string>
#include <any>
 
int main()
{
    const auto& s = std::make_any<std::string>("hello");
    
    if (s.type() == typeid(std::string))//刪除頂層cosnt和引用后的類型
    {
        auto a = std::any_cast<std::string>(s);
        std::cout << a << std::endl;
    }
 
    return 0;
}

結(jié)果如下:

如果類型不匹配轉(zhuǎn)換失敗了,傳遞一個地址將會返回nullptr:

auto a = std::make_any<std::string>("hello");
std::any_cast<std::string>(&a) // write-access via pointer
std::any_cast<const std::string>(&a); // read-access via pointer

注意,這里轉(zhuǎn)換到引用會導(dǎo)致運(yùn)行時錯誤:

std::any_cast<std::string&>(&a); // RUN-TIME ERROR

3. 修改值

相應(yīng)的賦值和emplace()操作。例如:

#include <iostream>
#include <string>
#include <any>
#include <complex>
 
int main()
{
    std::any a;
    a = 42; // a contains value of type int
    a = "hello"; // a contains value of type const char*
 
    a.emplace<std::string>("hello world");// a contains value of type std::string
 
    return 0;
}

結(jié)果如下:

4. 移動語法 

    std: any也支持移動語義。但是,請注意,move語義必須滿足包含的類型具有可復(fù)制構(gòu)造函數(shù)。也就是說,不支持只移動類型作為包含值類型。處理move語義的最佳方法可能并不明顯。所以,你應(yīng)該這樣做:

std::string s("hello, world!");
std::any a;
a = std::move(s); // move s into a
s = std::move(std::any_cast<string&>(a)); // move assign string in a to s

 與通常的從對象移動的情況一樣,在最后一次調(diào)用之后,所包含的值a是未指定的。因此,可以使用a作為字符串,只要沒有對所包含的字符串值的值做任何假設(shè)。

注意:

s = std::any_cast<string>(std::move(a));

也可以,但需要一個額外的移動。然而,以下內(nèi)容是危險(xiǎn)的(盡管它是c++標(biāo)準(zhǔn)中的一個例子):

std::any_cast<string&>(a) = std::move(s2); // OOPS: a to hold a string

只有當(dāng)包含的值已經(jīng)是字符串時,才可以這樣做。如果沒有,轉(zhuǎn)換將拋出一個std::bad_any_cast異常。

到此這篇關(guān)于C++17之std::any的具體使用的文章就介紹到這了,更多相關(guān)C++17 std::any內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • C++中unordered_set哈希集合的實(shí)現(xiàn)

    C++中unordered_set哈希集合的實(shí)現(xiàn)

    std::unordered_set是C++標(biāo)準(zhǔn)庫中的無序關(guān)聯(lián)容器,基于哈希表實(shí)現(xiàn),具有元素唯一性和無序性特點(diǎn),本文就來詳細(xì)的介紹一下unordered_set的使用,感興趣的可以了解一下
    2025-11-11
  • C與C++中結(jié)構(gòu)體的區(qū)別

    C與C++中結(jié)構(gòu)體的區(qū)別

    C中的結(jié)構(gòu)體只涉及到數(shù)據(jù)結(jié)構(gòu),而不涉及到算法,也就是說在C中數(shù)據(jù)結(jié)構(gòu)和算法是分離的,而到C++中一類或者一個結(jié)構(gòu)體可以包含函數(shù)(這個函數(shù)在C++我們通常中稱為成員函數(shù)),C++中的結(jié)構(gòu)體和類體現(xiàn)了數(shù)據(jù)結(jié)構(gòu)和算法的結(jié)合
    2013-10-10
  • C++從匯編的視角審視對象的創(chuàng)建問題

    C++從匯編的視角審視對象的創(chuàng)建問題

    這篇文章主要介紹了C++從匯編的視角看對象的創(chuàng)建,從匯編的視角來看,調(diào)用構(gòu)造器和調(diào)用 “返回對象” 的函數(shù)是一樣的,從匯編的角度來看,對象就是一堆數(shù)據(jù)的排列,比如說最普通的對象就是數(shù)據(jù)成員按照聲明順序直接排列,需要的朋友可以參考下
    2022-01-01
  • C語言入門學(xué)習(xí)筆記之typedef簡介

    C語言入門學(xué)習(xí)筆記之typedef簡介

    typedef為C語言的關(guān)鍵字,作用是為一種數(shù)據(jù)類型定義一個新名字,下面這篇文章主要給大家介紹了關(guān)于C語言入門學(xué)習(xí)筆記之typedef簡介的相關(guān)資料,需要的朋友可以參考下
    2021-11-11
  • C++實(shí)現(xiàn)LeetCode(84.直方圖中最大的矩形)

    C++實(shí)現(xiàn)LeetCode(84.直方圖中最大的矩形)

    這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(84.直方圖中最大的矩形),本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-07-07
  • C語言實(shí)現(xiàn)簡單推箱子小游戲

    C語言實(shí)現(xiàn)簡單推箱子小游戲

    這篇文章主要為大家詳細(xì)介紹了C語言實(shí)現(xiàn)推箱子小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-11-11
  • C++堆(Heap)與棧(Stack)內(nèi)存詳解

    C++堆(Heap)與棧(Stack)內(nèi)存詳解

    這篇文章主要介紹了C++堆(Heap)與棧(Stack)內(nèi)存詳解,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2026-05-05
  • C語言可變長的參數(shù)列表詳解

    C語言可變長的參數(shù)列表詳解

    這篇文章主要為大家介紹了C語言可變長的參數(shù)列表,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-01-01
  • Qt使用QWT繪制柱狀圖詳解

    Qt使用QWT繪制柱狀圖詳解

    QT中提供了一個叫做QWT的庫。QWT,全稱是Qt?Widgets?for?Technical?Applications,是一個基于LGPL版權(quán)協(xié)議的開源項(xiàng)目,可生成各種統(tǒng)計(jì)圖。本文將通過它繪制柱狀圖,需要的可以參考一下
    2022-01-01
  • C++中實(shí)現(xiàn)調(diào)試日志輸出

    C++中實(shí)現(xiàn)調(diào)試日志輸出

    在?C++?編程中,調(diào)試日志對于定位問題和優(yōu)化代碼至關(guān)重要,本文將介紹幾種常用的調(diào)試日志輸出方法,并教你如何在日志中添加時間戳,希望對大家有所幫助
    2025-01-01

最新評論

涿州市| 焉耆| 瑞丽市| 沛县| 济南市| 巧家县| 和田县| 黄浦区| 田阳县| 四川省| 黔江区| 奎屯市| 民丰县| 陆河县| 汶川县| 德令哈市| 竹溪县| 万宁市| 周至县| 毕节市| 西宁市| 仁怀市| 灵川县| 海阳市| 沛县| 大姚县| 桐梓县| 乌兰浩特市| 神木县| 嵊泗县| 游戏| 合水县| 紫金县| 博客| 台湾省| 盘锦市| 堆龙德庆县| 射洪县| 通州市| 延津县| 长阳|