c++ 模板之 std::enable_if_t 理解.
源码:
/// Alias template for enable_if
template<bool _Cond, typename _Tp = void>
using enable_if_t = typename enable_if<_Cond, _Tp>::type;
/// 因为 enable_if_t = typename enable_if<_Cond, _Tp>::type. 所以如果
// enable_if<_Cond, _Tp>::type 不存在,就导致 enable_if_t 不存在
// 在看 enable_if 存在2个。一个是
// enable_if<bool,_Tp> 类形
// 还有一个是 enable_if<true,_Tp>.
// 明显第二个是第一个的偏特化。
// 第一个,第二个的区别在于。第一个没有 type 类型
// 第二个有type 类型.
// enable_if_t = typename enable_if<_Cond, _Tp>::type。 就要看 _Cond = true还是 false。去匹配第一个还是第二个.匹配第一个,不好意思没有 type 类型,那么这个模板,就无法匹配到。 匹配到第二个,那就说明可以匹配.
// 第一个
// Primary template.
/// Define a member typedef @c type only if a boolean constant is true.
template<bool, typename _Tp = void>
struct enable_if
{ };
// 第二个
// Partial specialization for true.
template<typename _Tp>
struct enable_if<true, _Tp>
{ typedef _Tp type; };
下面就上面的代码写2个demo.
#define COND true
template <typename T, typename type = std::enable_if_t<COND,T>>
T & getT(T & t){
std::cout << __LINE__ <<"line_"<< std::endl;
return t;
}
template <typename T, typename = std::enable_if_t<COND,T>>
class testT{
public:
};
testT<int> t;