C++ Library Extensions 2022.12.09
To help learn modern C++ programming
12_sfinae.cpp
Go to the documentation of this file.
1#include <tpf_output.hpp>
2
5
6/*
7 type of enable_if_st is defined only when
8 the first non-type value is true
9 */
10template<bool predicate, typename ReturnType = void>
11struct enable_if // we assume predicate == false
12{
13 // using type = void;
14};
15
16template<typename ReturnType> // we cannot provide default value (or type) for specialization
17struct enable_if<true, ReturnType> // for specialization
18{
19 using type = ReturnType;
20};
21
22template<bool predicate, typename ReturnType=void>
24
25template<typename Type>
27
28template<typename Type>
30
31// this function is enabled or exists only when Type == int
32template<typename Type>
33enable_if_int_t<Type> // return type
34remainder(Type n, Type d)
35{
36 return n % d;
37}
38
39// this function exists only when Type == double
40template<typename Type>
41enable_if_double_t<Type> // return type
42remainder(Type n, Type d)
43{
44 long long q = (long long) n / d;
45
46 return (n - q * d);
47}
48
50{
51 auto d = remainder(7.0, 4.0);
52 auto i = remainder(7, 4);
53
54 stream << "The remainder of 7.0 divided by 4.0 = "
55 << d <<", type of d = " << Tpf_GetTypeCategory(d) << endl;
56
57 stream << "The remainder of 7 divided by 4 = "
58 << i <<", type of i = " << Tpf_GetTypeCategory(i) << endl;
59
60}
61
62int main()
63{
65}
66
enable_if_t< std::is_same_v< Type, double >, Type > enable_if_double_t
Definition: 12_sfinae.cpp:29
enable_if_int_t< Type > remainder(Type n, Type d)
Definition: 12_sfinae.cpp:34
tpf::sstream stream
Definition: 12_sfinae.cpp:3
void test_remainder()
Definition: 12_sfinae.cpp:49
enable_if_t< std::is_same_v< Type, int >, Type > enable_if_int_t
Definition: 12_sfinae.cpp:26
auto endl
Definition: 12_sfinae.cpp:4
typename enable_if< predicate, ReturnType >::type enable_if_t
Definition: 12_sfinae.cpp:23
int main()
Definition: 12_sfinae.cpp:62
constexpr auto endl
Definition: tpf_output.hpp:973
Stream output operators << are implemented.
#define Tpf_GetTypeCategory(instance_arg)
A macro that returns instance_arg's type category string name.
Definition: tpf_types.hpp:1428