作为一个标准的C++模板类,我们先看下enable_if的定义:
- // STRUCT TEMPLATE enable_if
- template <bool _Test, class _Ty = void>
- struct enable_if {}; // no member "type" when !_Test
-
- template <class _Ty>
- struct enable_if<true, _Ty> { // type is _Ty for _Test
- using type = _Ty;
- };
SFINAE
再说清楚这部分代码之前,我们先来说明一下SFINAE(
Substitution failure is not an error)的原理,先给一个实例:
- #include
- #include
-
- template<bool, typename T = void> // #1
- struct test_SFINAE {
- };
-
- template<typename T> // #2, partial specialization
- struct test_SFINAE<true, T> { //
- typedef int type;
- };
-
- template<typename T, typename test_SFINAE
::value, bool>::type = 0> - // #3
- void test_SFINAE_func() // Only T is int