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>
所以整体推导推导策略为,若测试类型有操作符++的实现:
- 无论operator++返回值是何种类型,包括void,均认为是支持;
- 隐式转换后的类型支持operator++(在ADL的类型匹配中优先级高于any的模板构造函数即可),均认为是支持。