Boost中is_incrementable實現細節推敲

is_incrementable.hpp代碼閱讀中的template實現細節推敲, 如代碼註釋:

namespace boost { namespace detail {
// is_incrementable<T> metafunction
//
// Requires: Given x of type T&, if the expression ++x is well-formed
// it must have complete type; otherwise, it must neither be ambiguous
// nor violate access.
// This namespace ensures that ADL doesn't mess things up.
namespace is_incrementable_
{
  // a type returned from operator++ when no increment is found in the
  // type's own namespace
  struct tag {};  //測試函數的返回值用
  
  // any soaks up implicit conversions and makes the following
  // operator++ less-preferred than any other such operator that
  // might be found via ADL.
  struct any { template <class T> any(T const&); }; //測試函數的入參隱式類型轉換用
  
  // 所有未定義++操作符的類型都會調用any的構造函數,進行隱式類型轉換,而後調用如下操作符函數
  // 此時返回值爲操作符調用的返回值爲tag
  tag operator++(any const&);
  tag operator++(any const&,int);
  
  // In case an operator++ is found that returns void, we'll use ++x,0
  // tag類型的逗號表達式特殊處理,否則(tag, int)的返回值爲int類型,導致後續的測試函數匹配通過
  tag operator,(tag,int);

  // 定義逗號表達式,規避返回值爲void類型的情況
  // 若某函數返回值爲void,如void ReturnVoid(),則下述測試代碼:
  // std::cout << (ReturnVoid(), 10) << std::endl;的輸出爲:10
  // 其中表達式前後的括號是必須的
  # define BOOST_comma(a,b) (a,b)

  // two check overloads help us identify which operator++ was picked
  //  check_測試函數,使用編譯器的SFINAE技巧,篩選不支持操作符的類型
  char (& check_(tag) )[2];  //check_函數返回值爲char[2]-char類型數組引用,注意函數返回值不能爲數組類型
  template <class T>
  char check_(T const&);
  
  template <class T>
  struct impl
  {
      static typename boost::remove_cv<T>::type& x;
      BOOST_STATIC_CONSTANT(
          bool
          //1. 需要逗號表達時包裹一下,否則會在++x返回值爲void類型時,
          //check函數的入參爲void const&類型,不合法參數導致編譯失敗
          //2. check_返回char爲測試通過,返回爲char&[2]測試失敗
        , value = sizeof(is_incrementable_::check_(BOOST_comma(++x,0))) == 1
      );
  };
  
  template <class T>
  struct postfix_impl
  {
      static typename boost::remove_cv<T>::type& x;
      BOOST_STATIC_CONSTANT(
          bool
        , value = sizeof(is_incrementable_::check_(BOOST_comma(x++,0))) == 1
      );
  };
# if defined(BOOST_MSVC)
#  pragma warning(pop)
# endif
}

//去掉宏定義,避免頭文件包含中同名宏定義的覆蓋
# undef BOOST_comma

template<typename T>
struct is_incrementable :
    public boost::integral_constant<bool, boost::detail::is_incrementable_::impl<T>::value>
{
	//看了下枚舉展開,定義了rebind函數,具體什麼用途不是很清楚
    BOOST_MPL_AUX_LAMBDA_SUPPORT(1,is_incrementable,(T))
};
template<typename T>
struct is_postfix_incrementable :
    public boost::integral_constant<bool, boost::detail::is_incrementable_::postfix_impl<T>::value>
{
    BOOST_MPL_AUX_LAMBDA_SUPPORT(1,is_postfix_incrementable,(T))
};
} // namespace detail
} // namespace boost
# include <boost/type_traits/detail/bool_trait_undef.hpp>

所以整體推導推導策略爲,若測試類型有操作符++的實現:

  1. 無論operator++返回值是何種類型,包括void,均認爲是支持;
  2. 隱式轉換後的類型支持operator++(在ADL的類型匹配中優先級高於any的模板構造函數即可),均認爲是支持。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章