function object研究之五

來源:互聯網
上載者:User
巧妙的檢測預留位置

boost提供了從_1到_9的預留位置,它們是9個變數。這些變數本質上都是一個模板類的執行個體化對象,特殊之處在於這個模板類arg<> 只接收1-9 的整數作為模板參數。下面詳細介紹如何檢測模板參數,並且當模板參數不符合要求時如何做到編譯報錯。

具體定義如下:

boost::arg<1> _1;boost::arg<2> _2;boost::arg<3> _3;boost::arg<4> _4;boost::arg<5> _5;boost::arg<6> _6;boost::arg<7> _7;boost::arg<8> _8;boost::arg<9> _9;template< int I > struct arg{    arg()    {    }    template< class T > arg( T const & /* t */ )    {        // static assert I == is_placeholder<T>::value        typedef char T_must_be_placeholder[ I == is_placeholder<T>::value? 1: -1 ];    }};template< int I > bool operator==( arg<I> const &, arg<I> const & ){    return true;}template< int I > struct is_placeholder< arg<I> >{    enum _vt { value = I };};template< int I > struct is_placeholder< arg<I> (*) () >{    enum _vt { value = I };};template< class T > struct is_placeholder{    enum _vt { value = 0 };};

說明:

1. arg<>模板類有兩個建構函式,預設建構函式在運行時調用。模板建構函式在編譯時間被調用,它才是真正接受了1-9整數參數的函數。但是為什麼class T居然是arg<1>類型,現在還不知道原因。

2.is_placeholder在這裡做了分析http://blog.csdn.net/sheismylife/article/details/8268644

3.利用數組的初始化長度不能小於0,來做編譯期檢測。

typedef char T_must_be_placeholder[ I == is_placeholder<T>::value? 1: -1 ];

這句話首先用了一個char數組,數組名字的意思就是 T必須是一個placeholder。placeholder就是arg<1>到arg<9>這9個全域變數,或者寫成_1到_9.

如果將_1或者_9作為參數構造boost::arg對象,編譯會通過。因為is_placeholder<_1>::value的值肯定是1,再和I比較,I本來也是1,因此I==is_placeholder<T>::value的結果是true,最終數組長度為1.

但是如果傳遞的是_1到_9之外的參數,數組長度為-1. 編譯器會報錯:

boost::arg<1> arg1(_1);//編譯通過,因為_1是預留位置string str;boost::arg<1> arg2(str);//編譯不通過,因為str不是預留位置

/usr/src/boost_1_47_0/boost/bind/arg.hpp: In constructor ‘boost::arg<I>::arg(const T&) [with T = std::basic_string<char>, int I = 1]’:In file included from /usr/src/boost_1_47_0/boost/bind/bind.hpp:29:0, from /usr/src/boost_1_47_0/boost/bind.hpp:22, from main.cpp:12:main.cpp:59:27: instantiated from here/usr/src/boost_1_47_0/boost/bind/arg.hpp:37:22: error: size of array is negative

這也說明==,?:操作符都是可以在編譯期間求值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.