sfinae

Approaches to function SFINAE in C++

扶醉桌前 提交于 2020-07-16 16:18:31
问题 I am using function SFINAE heavily in a project and am not sure if there are any differences between the following two approaches (other than style): #include <cstdlib> #include <type_traits> #include <iostream> template <class T, class = std::enable_if_t<std::is_same_v<T, int>>> void foo() { std::cout << "method 1" << std::endl; } template <class T, std::enable_if_t<std::is_same_v<T, double>>* = 0> void foo() { std::cout << "method 2" << std::endl; } int main() { foo<int>(); foo<double>();

“Inverse SFINAE” to avoid ambiguous overload

一笑奈何 提交于 2020-06-29 07:03:54
问题 How can I prevent the first template below from instantiating if the second template instantiates? (i.e. if both static_cast<T>(0) and T::zero() are defined) template<typename T> auto zero() ->decltype(static_cast<T>(0)) { return static_cast<T>(0); } template<typename T> auto zero() ->decltype(T::zero()) { return T::zero(); } 回答1: If you need to extend it to multiple overloads with fine grained control of overload rank, a common technique is to use tag dispatching. template<int r> struct rank

“Inverse SFINAE” to avoid ambiguous overload

萝らか妹 提交于 2020-06-29 07:03:34
问题 How can I prevent the first template below from instantiating if the second template instantiates? (i.e. if both static_cast<T>(0) and T::zero() are defined) template<typename T> auto zero() ->decltype(static_cast<T>(0)) { return static_cast<T>(0); } template<typename T> auto zero() ->decltype(T::zero()) { return T::zero(); } 回答1: If you need to extend it to multiple overloads with fine grained control of overload rank, a common technique is to use tag dispatching. template<int r> struct rank