看見別人的
帖子,也做了下。
代碼只支持內(nèi)建類型。
1
#include <iostream>
2
3
template<bool, typename T, typename F>
4
struct Select_type
{ typedef T R; };
5
6
template<typename T, typename F>
7
struct Select_type<false, T, F>
{ typedef F R; };
8
9
template<typename T, typename S>
10
struct Larger_type
{
11
typedef typename Select_type<sizeof(T) >= sizeof(S), T, S>::R R;
12
};
13
14
template<typename T, typename S>
15
typename Larger_type<T, S>::R min_value(T a, S b)
16

{
17
return a < b ? a : b;
18
}
19
20
21
int main()
22

{
23
int a = 2;
24
double b = 1.2;
25
std::cout << min_value(a, b) << " " << min_value(b, a) << "\n";
26
}
27
28
浮點(diǎn)數(shù)與整型進(jìn)行比較時(shí),默認(rèn)整型轉(zhuǎn)為浮點(diǎn)數(shù)

template<bool, typename T, typename F>

struct Select_type
{ typedef T R; };

template<typename T, typename F>

struct Select_type<false, T, F>
{ typedef F R; };

template<typename T> struct Type_rank


{ static const int rank = 0; };

template<> struct Type_rank<float>


{ static const int rank = 21; };

template<> struct Type_rank<double>


{ static const int rank = 22; };

template<> struct Type_rank<long double>


{ static const int rank = 23; };

template<typename T, typename S>

struct Larger_type
{
static const int fa = Type_rank<T>::rank;
static const int fb = Type_rank<S>::rank;
static const bool flag = fa > fb || (fa == fb && sizeof(T) >= sizeof(S));
typedef typename Select_type<flag, T, S>::R R;
};

template<typename T>

struct Larger_type<T, T>
{ typedef T R;};

template<typename T, typename S>
typename Larger_type<T, S>::R min_value(T a, S b)


{
return a < b ? a : b;
}
