• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>
            xiaoguozi's Blog
            Pay it forword - 我并不覺(jué)的自豪,我所嘗試的事情都失敗了······習(xí)慣原本生活的人不容易改變,就算現(xiàn)狀很糟,他們也很難改變,在過(guò)程中,他們還是放棄了······他們一放棄,大家就都是輸家······讓愛(ài)傳出去,很困難,也無(wú)法預(yù)料,人們需要更細(xì)心的觀察別人,要隨時(shí)注意才能保護(hù)別人,因?yàn)樗麄兾幢刂雷约阂裁础ぁぁぁぁ?/span>
            01.#include <iostream>  
            02.#include <list>  
            03.#include <boost/any.hpp>  
            04. 
            05.typedef std::list<boost::any> list_any;  
            06. 
            07.//關(guān)鍵部分:可以存放任意類(lèi)型的對(duì)象  
            08.void fill_list(list_any& la)  
            09.{      
            10.    la.push_back(10);//存放常數(shù)   
            11.    la.push_back( std::string("dyunze") );//存放字符串對(duì)象;注意la.push_back(“dyunze”)錯(cuò)誤,因?yàn)闀?huì)被當(dāng)錯(cuò)字符串?dāng)?shù)組  
            12.}  
            13. 
            14.//根據(jù)類(lèi)型進(jìn)行顯示  
            15.void show_list(list_any& la)  
            16.{  
            17.    list_any::iterator it;  
            18.    boost::any anyone;  
            19. 
            20.    for( it = la.begin(); it != la.end(); it++ )  
            21.    {     
            22.        anyone = *it;  
            23. 
            24.        if( anyone.type() == typeid(int) )  
            25.            std::cout<<boost::any_cast<int>(*it)<<std::endl;  
            26.        else if( anyone.type() == typeid(std::string) )  
            27.            std::cout<<boost::any_cast<std::string>(*it).c_str()<<std::endl;  
            28.    }  
            29.}  
            30. 
            31.int main()  
            32.{  
            33.    list_any la;  
            34.    fill_list(la);  
            35.    show_list(la);  
            36. 
            37.    return 0;  
            38.} 
            #include <iostream>
            #include <list>
            #include <boost/any.hpp>

            typedef std::list<boost::any> list_any;

            //關(guān)鍵部分:可以存放任意類(lèi)型的對(duì)象
            void fill_list(list_any& la)
            {   
                la.push_back(10);//存放常數(shù)
                la.push_back( std::string("dyunze") );//存放字符串對(duì)象;注意la.push_back(“dyunze”)錯(cuò)誤,因?yàn)闀?huì)被當(dāng)錯(cuò)字符串?dāng)?shù)組
            }

            //根據(jù)類(lèi)型進(jìn)行顯示
            void show_list(list_any& la)
            {
                list_any::iterator it;
                boost::any anyone;

                for( it = la.begin(); it != la.end(); it++ )
                {   
                    anyone = *it;

                    if( anyone.type() == typeid(int) )
                        std::cout<<boost::any_cast<int>(*it)<<std::endl;
                    else if( anyone.type() == typeid(std::string) )
                        std::cout<<boost::any_cast<std::string>(*it).c_str()<<std::endl;
                }
            }

            int main()
            {
                list_any la;
                fill_list(la);
                show_list(la);

                return 0;
            }

            boost::any的優(yōu)點(diǎn):

                 對(duì)設(shè)計(jì)模式理解的朋友都會(huì)知道合成模式。因?yàn)槎鄳B(tài)只有在使用指針或引用的情況下才能顯現(xiàn),所以std容器中只能存放指針或引用(但實(shí)際上只能存放指針,無(wú)法存放引用,這個(gè)好像是c++的不足吧)。如:

                 std::list<BaseClass*> mylist;

            這樣,我們就要對(duì)指針?biāo)赶騼?nèi)容的生存周期操心(可能需要程序員適時(shí)刪除申請(qǐng)的內(nèi)存;但是由于存放指針,插入/刪除的效率高),而使用boost::any就可能避免這種情況,因?yàn)槲覀兛梢源娣蓬?lèi)型本身(當(dāng)然存放指針也可以)。這是boost::any的優(yōu)點(diǎn)之一。

                boost::any另一個(gè)優(yōu)點(diǎn)是可以存放任何類(lèi)型。而前面提到的mylist只能存放BaseClass類(lèi)指針以及其繼承類(lèi)的指針。

            boost::any的缺點(diǎn):

                由于boost::any可以存放任何類(lèi)型,自然它用不了多態(tài)特性,沒(méi)有統(tǒng)一的接口,所以在獲取容器中的元素時(shí)需要實(shí)現(xiàn)判別元素的真正類(lèi)型,這增加了程序員的負(fù)擔(dān)。與面向?qū)ο缶幊趟枷胗行┟?,但整個(gè)標(biāo)準(zhǔn)c++模板庫(kù)何嘗不是如此,用那些牛人的話來(lái)說(shuō),是“有益補(bǔ)充”。

               總之,有利必有弊,沒(méi)有十全十美的。

              

            分析并模仿boost::any:

                 讀了一下boost::any的源代碼,并模仿一下其實(shí)現(xiàn)(相當(dāng)一部分時(shí)拷貝原代碼),下面是代碼(只包含必要功能)。

            實(shí)現(xiàn)any的功能主要由三部分組成:
            1)any類(lèi)
            2)真正保存數(shù)據(jù)的holder類(lèi)及其基類(lèi)placeholder
            3)獲取真正數(shù)據(jù)的模板函數(shù)any_cast,類(lèi)型轉(zhuǎn)換的功能。

            view plaincopy to clipboardprint?
            01.#include <iostream>  
            02.#include <list>  
            03.#include <cassert>  
            04. 
            05.//自定義的any類(lèi)  
            06.class any  
            07.{  
            08.public:  
            09.      
            10.    //保存真正數(shù)據(jù)的接口類(lèi)  
            11.    class placeholder  
            12.    {  
            13.    public:       
            14.        virtual ~placeholder()  
            15.        {  
            16.        }  
            17.    public:   
            18. 
            19.        virtual const std::type_info & type() const = 0;  
            20.        virtual placeholder * clone() const = 0;      
            21.    };  
            22. 
            23.    //真正保存和獲取數(shù)據(jù)的類(lèi)。  
            24.    template<typename ValueType>  
            25.    class holder : public placeholder  
            26.    {  
            27.    public:           
            28.        holder(const ValueType & value): held(value)  
            29.        {  
            30.        }  
            31. 
            32.    public:   
            33. 
            34.        virtual const std::type_info & type() const 
            35.        {  
            36.            return typeid(ValueType);  
            37.        }  
            38. 
            39.        virtual placeholder * clone() const 
            40.        {  
            41.            return new holder(held);//使用了原型模式  
            42.        }  
            43. 
            44.    public:   
            45. 
            46.        //真正的數(shù)據(jù),就保存在這里  
            47.        ValueType held;  
            48.    };  
            49. 
            50.public:  
            51. 
            52.    any(): content(NULL)     
            53.    {         
            54.    }  
            55. 
            56.    //模板構(gòu)造函數(shù),參數(shù)可以是任意類(lèi)型,真正的數(shù)據(jù)保存在content中  
            57.    template<typename ValueType>  
            58.    any(const ValueType & value): content(new holder<ValueType>(value))  
            59.    {  
            60.    }    
            61. 
            62.    //拷貝構(gòu)造函數(shù)  
            63.    any(const any & other)  
            64.        : content(other.content ? other.content->clone() : 0)  
            65.    {  
            66.    }  
            67. 
            68.    //析構(gòu)函數(shù),刪除保存數(shù)據(jù)的content對(duì)象  
            69.    ~any()  
            70.    {  
            71.        if(NULL != content)  
            72.            delete content;  
            73.    }  
            74. 
            75.private:  
            76.    //一個(gè)placeholde對(duì)象指針,指向其子類(lèi)folder的一個(gè)實(shí)現(xiàn)  
            77.    // 即content( new holder<ValueType>(value) )語(yǔ)句  
            78.    placeholder* content;  
            79. 
            80.    template<typename ValueType> friend ValueType any_cast(const any& operand);  
            81.public:   
            82. 
            83.    //查詢真實(shí)數(shù)據(jù)的類(lèi)型。  
            84.    const std::type_info & type() const 
            85.    {  
            86.        return content ? content->type() : typeid(void);  
            87.    }  
            88.};  
            89. 
            90. 
            91.//獲取content->helder數(shù)據(jù)的方法。用來(lái)獲取真正的數(shù)據(jù)  
            92.template<typename ValueType>  
            93.ValueType any_cast(const any& operand)  
            94.{  
            95.    assert( operand.type() == typeid(ValueType) );  
            96.    return static_cast<any::holder<ValueType> *>(operand.content)->held;  
            97.}  
            98. 
            99.//下代碼是使用示例  
            100. 
            101.typedef std::list<any> list_any;  
            102. 
            103.void fill_list(list_any& la)  
            104.{      
            105.    la.push_back(10);//存放常數(shù);調(diào)用了any的模板構(gòu)造函數(shù),下同  
            106.    la.push_back( std::string("我是string") );//存放字符串對(duì)象;注意la.push_back(“dyunze”)錯(cuò)誤,因?yàn)闀?huì)被當(dāng)錯(cuò)字符串?dāng)?shù)組  
            107. 
            108.    char* p = "我是常量區(qū)字符串a(chǎn)bc";  
            109.    la.push_back(p);//可以存放指針,但要注意指針的失效問(wèn)題  
            110.}  
            111. 
            112.//根據(jù)類(lèi)型進(jìn)行顯示  
            113.void show_list(list_any& la)  
            114.{  
            115.    list_any::iterator it;  
            116. 
            117.    for( it = la.begin(); it != la.end(); it++ )  
            118.    {     
            119. 
            120.        if( (*it).type() == typeid(int) )  
            121.            std::cout<<any_cast<int>(*it)<<std::endl;  
            122.        else if( (*it).type() == typeid(std::string) )  
            123.            std::cout<<any_cast<std::string>(*it).c_str()<<std::endl;  
            124.        else if( (*it).type() == typeid(char*) )  
            125.            std::cout<<any_cast<char*>(*it)<<std::endl;  
            126.    }  
            127.}  
            128. 
            129.int main()  
            130.{  
            131.    list_any la;  
            132.    fill_list(la);  
            133.    show_list(la);  
            134. 
            135.    return 0;  
            136.} 

             boost::any是一個(gè)很有趣的類(lèi),剛剛開(kāi)始我還以為其就是一個(gè)variant類(lèi)型,
            能夠?qū)⑷我忸?lèi)型值保存進(jìn)去,能夠以任意類(lèi)型值讀出來(lái),不過(guò)我錯(cuò)了 :(
              boost::any的作者認(rèn)為,所謂generic type有三個(gè)層面的解釋方法:
              1.類(lèi)似variant類(lèi)型那樣任意進(jìn)行類(lèi)型轉(zhuǎn)換,可以保存一個(gè)(int)5進(jìn)去,
                讀一個(gè)(string)"5"出來(lái)。Win下面的VARIANT類(lèi)型是以一個(gè)巨大的
                union實(shí)現(xiàn)的類(lèi)似功能,使用靈活但效率較低
              2.區(qū)別對(duì)待包含值的類(lèi)型,保存一個(gè)(int)5進(jìn)去,不會(huì)被隱式轉(zhuǎn)換為
                (string)'5'或者(double)5.0,這樣效率較高且類(lèi)型安全,
                不必?fù)?dān)心ambiguous conversions
              3.對(duì)包含值類(lèi)型不加區(qū)別,例如把所有保存的值強(qiáng)制轉(zhuǎn)換為void *保存
                讀取時(shí)再有程序員判斷其類(lèi)型。這樣效率雖最高但無(wú)法保證類(lèi)型安全
              boost::any就選擇了第二層面的設(shè)計(jì)思路,它允許用戶將任意類(lèi)型值保存
            進(jìn)一個(gè)any類(lèi)型變量,但內(nèi)部并不改變值的類(lèi)型,并提供方法讓用戶在使用時(shí)
            主動(dòng)/被動(dòng)進(jìn)行類(lèi)型判斷。

              在實(shí)現(xiàn)方面,boost::any使用兩層內(nèi)部類(lèi)placeholder和holder保存
            實(shí)際類(lèi)型的值。類(lèi)placeholder只是一個(gè)接口,模板類(lèi)holder是特定類(lèi)型
            的實(shí)現(xiàn)。其中type()方法獲取實(shí)際值類(lèi)型,即typeid(ValueType);
            clone()方法獲取值的拷貝return new holder(held);
              virtual const std::type_info & type() const
              virtual placeholder * clone() const
              其值的類(lèi)型信息不象Win的VARIANT那樣以專(zhuān)門(mén)的字段保存,
            而是通過(guò)模板參數(shù)形式靜態(tài)保存。這樣效率更高(僅在編譯期),

            通用性更強(qiáng)(任何類(lèi)型都可以,真正any)但靈活性不如VARIANT
              在進(jìn)行拷貝構(gòu)造/賦值/swap時(shí),都直接將整個(gè)placeholder換掉,
            這樣可以保證值類(lèi)型的延續(xù)性。

              在使用方面,提供了主動(dòng)/被動(dòng)進(jìn)行類(lèi)型檢測(cè)的方法。
              可以使用any::type()方法主動(dòng)檢測(cè)值類(lèi)型
            bool is_int(const boost::any & operand)
            {
                return operand.type() == typeid(int);
            }
              也可以通過(guò)any_cast函數(shù)被動(dòng)進(jìn)行檢測(cè)。此函數(shù)與C++中的*_cast
            系列關(guān)鍵字有相同的語(yǔ)法規(guī)范,嘗試進(jìn)行類(lèi)型轉(zhuǎn)換,如類(lèi)型不匹配則對(duì)
            指針轉(zhuǎn)換返回NULL,對(duì)引用轉(zhuǎn)換拋出boost::bad_any_cast異常
              boost::any str = string("12345");
              try
              {
                cout << boost::any_cast<int>(str) << endl;
              }
              catch(boost::bad_any_cast e)
              {
                cerr << e.what() << endl;
              }


              在應(yīng)用方面,any類(lèi)型適合于類(lèi)型不同但使用相關(guān)的值。如C++的...
            形式的函數(shù)參數(shù)本事不是類(lèi)型安全的,可以通過(guò)vector<any>改造之
            然后在使用時(shí)檢測(cè)類(lèi)型是否匹配,如可改造printf為
              void safe_printf(const char *format, const vector<any>& params)
              {
                int index = 0;
                for(const char *pch = format; *pch; pch++)
                {
                  switch(*pch)
                  {
                    case '%':
                    {
                      switch(*++pch)
                      {
                        case 'i':
                        case 'd':
                        {
                          if(params[index].type() == typeid(int) ||
                             params[index].type() == typeid(short))
                          {
                            ...
                          }
                          else
                            throw ...
                        }
                      }
                    }
                    case '\':
                    {
                      ...
                    }
                    default:
                    {
                      putchar(*pch);
                    }
                  }
                }
              }

            附:boost::any.hpp
            #ifndef BOOST_ANY_INCLUDED
            #define BOOST_ANY_INCLUDED

            // what:  variant type boost::any
            // who:   contributed by Kevlin Henney,
            //        with features contributed and bugs found by
            //        Ed Brey, Mark Rodgers, Peter Dimov, and James Curran
            // when:  July 2001
            // where: tested with BCC 5.5, MSVC 6.0, and g++ 2.95

            #include <algorithm>
            #include <typeinfo>

            #include "boost/config.hpp"

            namespace boost
            {
                class any
                {
                public: // structors

                    any()
                      : content(0)
                    {
                    }

                    template<typename ValueType>
                    any(const ValueType & value)
                      : content(new holder<ValueType>(value))
                    {
                    }

                    any(const any & other)
                      : content(other.content ? other.content->clone() : 0)
                    {
                    }

                    ~any()
                    {
                        delete content;
                    }

                public: // modifiers

                    any & swap(any & rhs)
                    {
                        std::swap(content, rhs.content);
                        return *this;
                    }

                    template<typename ValueType>
                    any & operator=(const ValueType & rhs)
                    {
                        any(rhs).swap(*this);
                        return *this;
                    }

                    any & operator=(const any & rhs)
                    {
                        any(rhs).swap(*this);
                        return *this;
                    }

                public: // queries

                    bool empty() const
                    {
                        return !content;
                    }

                    const std::type_info & type() const
                    {
                        return content ? content->type() : typeid(void);
                    }

            #ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
                private: // types
            #else
                public: // types (public so any_cast can be non-friend)
            #endif


                    class placeholder
                    {
                    public: // structors
                
                        virtual ~placeholder()
                        {
                        }

                    public: // queries

                        virtual const std::type_info & type() const = 0;

                        virtual placeholder * clone() const = 0;
                
                    };

                    template<typename ValueType>
                    class holder : public placeholder
                    {
                    public: // structors

                        holder(const ValueType & value)
                          : held(value)
                        {
                        }

                    public: // queries

                        virtual const std::type_info & type() const
                        {
                            return typeid(ValueType);
                        }

                        virtual placeholder * clone() const
                        {

                            return new holder(held);
                        }

                    public: // representation

                        ValueType held;

                    };

            #ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS

                private: // representation

                    template<typename ValueType>
                    friend ValueType * any_cast(any *);

            #else

                public: // representation (public so any_cast can be non-friend)

            #endif

                    placeholder * content;

                };

                class bad_any_cast : public std::bad_cast
                {
                public:
                    virtual const char * what() const throw()
                    {
                        return "boost::bad_any_cast: "
                               "failed conversion using boost::any_cast";
                    }
                };

                template<typename ValueType>
                ValueType * any_cast(any * operand)
                {
                    return operand && operand->type() == typeid(ValueType)
                                ? &static_cast<any::holder<ValueType> *>(operand->content)->held
                                : 0;
                }

                template<typename ValueType>
                const ValueType * any_cast(const any * operand)
                {
                    return any_cast<ValueType>(const_cast<any *>(operand));
                }

                template<typename ValueType>
                ValueType any_cast(const any & operand)
                {
                    const ValueType * result = any_cast<ValueType>(&operand);
                    if(!result)
                        throw bad_any_cast();
                    return *result;
                }

            }

            // Copyright Kevlin Henney, 2000, 2001, 2002. All rights reserved.
            //
            // Permission to use, copy, modify, and distribute this software for any
            // purpose is hereby granted without fee, provided that this copyright and
            // permissions notice appear in all copies and derivatives.
            //
            // This software is provided "as is" without express or implied warranty.

            #endif

            posted on 2011-06-16 18:32 小果子 閱讀(858) 評(píng)論(0)  編輯 收藏 引用 所屬分類(lèi): C++
            亚洲精品高清国产一线久久| 久久九九亚洲精品| 国产91久久精品一区二区| 色欲综合久久躁天天躁| 久久99热狠狠色精品一区| 狠狠色婷婷久久综合频道日韩| 久久久精品2019免费观看 | 亚洲午夜久久久影院伊人| 久久天天躁狠狠躁夜夜不卡 | 中文字幕精品久久| 久久综合五月丁香久久激情| 精品久久久久久| 久久精品一区二区国产| 久久精品黄AA片一区二区三区| 2021最新久久久视精品爱| 亚洲人成电影网站久久| 国产精品永久久久久久久久久| 91精品国产高清久久久久久91| 99久久久久| 久久综合鬼色88久久精品综合自在自线噜噜 | 色欲久久久天天天综合网 | 三级三级久久三级久久| 久久婷婷五月综合国产尤物app | 久久国产香蕉视频| 久久亚洲熟女cc98cm| 久久久亚洲AV波多野结衣 | 久久综合香蕉国产蜜臀AV| 久久久精品免费国产四虎| 欧美午夜A∨大片久久| 亚洲综合日韩久久成人AV| 久久国产成人精品麻豆| 久久国产成人精品国产成人亚洲| 久久激情亚洲精品无码?V| 7777精品久久久大香线蕉| 国产成人精品久久亚洲高清不卡 | 中文字幕精品无码久久久久久3D日动漫| 亚洲中文字幕无码一久久区 | 日本人妻丰满熟妇久久久久久| 2021国产成人精品久久| 五月丁香综合激情六月久久| 久久成人精品|