Boost學習筆記2-Boost-Any

喜歡這篇文章嗎?喜歡的話去看博主的置頂博客,即可依據分類找到此文章的原版得到更好的體驗,

圖片及代碼顯示的問題,筆者深感抱歉,想要更好的體驗去原博文即可。


title: Boost學習筆記2 - Boost.Any
mathjax: true
date: 2020-03-17 13:40:35
categories: [c++筆記,Boost學習筆記]
tags: [c++筆記,Boost學習筆記]
keywords: [c++筆記,Boost學習筆記]


Boost.Any

   Any在C++17被編入STL
C++是強類型語言,沒有辦法向Python那樣把一個int賦值給一個double這種騷操作,而Boost.Any庫爲我們模擬了這個過程,使得我們可以實現弱類型語言的東西。

在基本數據類型中玩弱類型

#include <boost/any.hpp>
int main(){
  boost::any a = 1;
  a = 3.14;
  a = true;
}

   這樣的代碼是允許編譯的,大概是因爲boost::any內部儲存的是指針。

char數組不行了

#include <boost/any.hpp>
int main(){
  boost::any a = 1;
  a = "hello world";
}

   上訴代碼可以編譯和運行,但是一定會碰到問題的,當我們把char數組弄過去的時候,就不太行了,原因是char[]不支持拷貝構造,但是我們可以通過把std::string來解決這個問題。

用std::string代替char數組

#include <boost/any.hpp>
int main(){
  boost::any a = 1;
  a = std::string("hello world");
}

   可以見到我們用string完美地解決了這個問題。

寫很容易,如何讀呢?

   我們已經學習了boost::any的寫操作,但是應該如何讀取呢?

#include <boost/any.hpp>
#include <iostream>
int main(){
  boost::any a = 1;
  std::cout << boost::any_cast<int>(a) << std::endl;
}

   boost提供了一個模版函數any_cast<T>來對我們的any類進行讀取

類型不對會拋出異常

   有了any<T>的模版,看起來我們可以對boost進行任意讀取,我們試試下這個

#include <boost/any.hpp>
#include <iostream>
int main() {
  boost::any a = 1;
  a = "hello world";
  std::cout << boost::any_cast<int>(a) << std::endl;
}

   拋出瞭如下異常

libc++abi.dylib: terminating with uncaught exception of type boost::wrapexcept<boost::bad_any_cast>: boost::bad_any_cast: failed conversion using boost::any_cast

   實際上上訴代碼是永遠無法成功的。因爲你把一個char數組傳了進去。

成員函數

   boost的any是有很多成員函數的。比方說empty可以判斷是否爲空,type可以得到類型信息,

#include <boost/any.hpp>
#include <iostream>
#include <typeinfo>

int main() {
  boost::any a = std::string("asdf");
  if (!a.empty()) {
    std::cout << a.type().name() << std::endl;
    a = 1;
    std::cout << a.type().name() << std::endl;
  }
}

   代碼運行結果如下,表示首先是字符串,然後是整形。

NSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEE
i

拿到指針

   當我們把一個any的地址傳給any_cast的時候,我們會得到any內部數據的指針,

#include <boost/any.hpp>
#include <iostream>

int main()
{
  boost::any a = 1;
  int *i = boost::any_cast<int>(&a);
  std::cout << *i << std::endl;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章