Created
May 14, 2020 08:55
-
-
Save vasalf/a2af0c17fcb01486a51f29f98fcdda3d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// У нас есть специализация | |
template<class T> | |
class vector { | |
}; | |
template<> | |
class vector<bool> { | |
}; | |
// Темплейтная функция | |
template<class T> | |
typename T::S foo(const T& arg); | |
// Если типа T::S не существует, компилятор пойдёт искать дальше. | |
// enable_if | |
template<bool value, typename T> | |
struct enable_if {}; | |
template<typename T> | |
struct enable_if<true, T> { | |
typedef T type; | |
}; | |
// есть в std | |
template<int n> | |
typename std::enable_if<n % 2 == 1, int>::type foo(const std::array<int, n>& arg); | |
// Всякие предикаты из std | |
#include <type_traits> | |
std::is_integral<T>::value, std::is_integral_v<T>; | |
std::is_same<T, S>::value, std::is_same_v<T, S>; | |
// enable_if_t (C++17) | |
template<int n> | |
std::enable_if_t<n % 2 == 1, int> foo(const std::array<int, n>& arg); | |
template<bool val, typename T> | |
using enable_if_t = std::enable_if<val, T>::type; // есть в std | |
// Места, куда можно засунуть | |
template<typename T> | |
std::enable_if_t<std::is_integral_v<T>, T> sum(const std::vector<T>&); | |
template<typename T> | |
T sum(const std::enable_if_t<std::is_integral_v<T>, std::vector<T>>&); | |
// SFINAE в структурах | |
template<typename T, typename = void> | |
struct sum_calculator { | |
static constexpr bool instantiated = false; | |
}; | |
template<typename T> | |
struct sum_calculator<T, std::enable_if_t<std::is_integral_v<T>, void>> { | |
static constexpr bool instantiated = true; | |
T calculate(const std::vector<T>&); | |
}; | |
template<typename T> | |
std::enable_if_t<sum_calculator<T>::instantiated, T> sum(const std::vector<T>& v) { | |
return sum_calculator<T>().calculate(v); | |
} | |
// member check | |
decltype(v); | |
std::declval<T>(); | |
template<class T> | |
T declval(); | |
struct Ok { | |
int get() const; | |
}; | |
struct NotOk { | |
double get() const; | |
}; | |
struct NotOK2 {}; | |
template<class T> | |
std::enable_if< | |
std::is_same_v<int, decltype(declval<const T&>().get()), | |
int | |
> get(const T& v) { | |
return v.get(); | |
} | |
template<class T> | |
int get(const T& v) { | |
return v.get(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment