一個簡單的元編程例子

來源:互聯網
上載者:User

在asio中有這麼一段代碼

template <typename Stream><br />char is_read_buffered_helper(buffered_stream<Stream>* s);</p><p>template <typename Stream><br />char is_read_buffered_helper(buffered_read_stream<Stream>* s);</p><p>struct is_read_buffered_big_type { char data[10]; };<br />is_read_buffered_big_type is_read_buffered_helper(...);</p><p>} // namespace detail</p><p>/// The is_read_buffered class is a traits class that may be used to determine<br />/// whether a stream type supports buffering of read data.<br />template <typename Stream><br />class is_read_buffered<br />{<br />public:<br />#if defined(GENERATING_DOCUMENTATION)<br /> /// The value member is true only if the Stream type supports buffering of<br /> /// read data.<br /> static const bool value;<br />#else<br /> BOOST_STATIC_CONSTANT(bool,<br /> value = sizeof(detail::is_read_buffered_helper((Stream*)0)) == sizeof(char));<br />#endif<br />};

將它轉成一個通俗的問題:編譯期判斷某個類型是否是一個指標類型。

typedef char YES;<br />typedef short NO;</p><p>/////FUNCTION 1<br />template <typename T><br />YES IsPtrHelper(T* p);</p><p>/////FUNCTION 2<br />No IsPtrHelper(...);</p><p>template <typename T><br />bool IsPtr(const T& p)<br />{<br /> return sizeof(YES) == sizeof(IsPtrHelper(p));<br />}

 

兩個HELPER函數都無需定義。

編譯期間,根據參數類型,匹配其中一個函數,並檢查傳回型別的SIZEOF,一切都是編譯期確定,無需函數調用,所以也不需要提供定義。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.