在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,一切都是編譯期確定,無需函數調用,所以也不需要提供定義。