A tag of infinite

来源:互联网 发布:2015总决赛数据 编辑:程序博客网 时间:2024/05/17 05:11

infinite is a important concept in programming. the following is a class which implements this concept.

template<typename T> // T was supposed to be legal number types
class neg_infinite
{
public:
    explicit neg_infinite(){}
    bool operator<(T i){return true;}
    bool operator>(T i){return false;}
    friend bool operator<(T i, neg_infinite j){return false;}
    friend bool operator>(T i, neg_infinite j){return true;}
    bool operator==(T i){return false;}
    friend bool operator==(T i, neg_infinite j){return false;}
};
template<typename T>
class pos_infinite
{
public:
    explicit pos_infinite(){}
    bool operator<(T i){return false;}
    bool operator>(T i){return true;}
    friend bool operator<(T i, pos_infinite j){return true;}
    friend bool operator>(T i, pos_infinite j){return false;}
    bool operator==(T i){return false;}
    friend bool operator==(T i, pos_infinite j){return false;}
};

//how to use

neg_infinite<int>() < -999;  // true
pos_infinite<int>() == 999; // false
neg_infinite<int>() == neg_infinite<int>(); // insignificance, compiler-time error

if you want T to be primitive types, you needs to check it by following codes:

template<typename T>
class must_be_primitive_num
{
private:
 must_be_primitive_num(){}
};
template<>class must_be_primitive_num<int>{};
template<>class must_be_primitive_num<long>{};
template<>class must_be_primitive_num<short>{};
template<>class must_be_primitive_num<float>{};
template<>class must_be_primitive_num<double>{};
//...adding others primitive types to specialization

must_be_primitive_num<user_defined_type>(); will rise a compiler-time error.

but notice that the bad news is this tag can not push into a vector<int>, its usage is limited. to allowing this, int must be convert to class infinite. however, consideration of efficiency will prohibit this conversion even implict conversion is convenient.

in fact, a good consideration about programming does not need a concept of infinite because the math in programming language is no longer pure. the distinctions of numbers in math is categorial(R, N...) rather than the field of representation(a little categorial meaning, i.e. int and float). so every numbers used in programming lanuage has its extent, i.e. unsigned int has its range from 0 to 65535(32bit). if you know your code then you also clear about what infinite it is which corresponding to that variable.