Is the correct name enough for this to happen?

I just plunged in limits.hfrom Microsoft. I tried to check what the return type is for the function max(), and to my surprise, I see something like this:

// TEMPLATE CLASS numeric_limits
template<class _Ty>
    class numeric_limits
        : public _Num_base
    {   // numeric limits for arbitrary type _Ty (say little or nothing)
public:
    static _Ty (__CRTDECL min)() _THROW0()
        {   // return minimum value
        return (_Ty(0));
        }

    static _Ty (__CRTDECL max)() _THROW0()
        {   // return maximum value
        return (_Ty(0));//EXACTLY THE SAME WHAT IN min<<------------------
        }
//... other stuff
};

How is it possible that both in minand maxreturn exactly the same? Does this mean that if I wrote makeSanwich () return (_Ty (0)), it would make a sandwich for me? How is it possible that with the same code as with function names only, we get different results?

+3
source share
4 answers

. , - :

template<>
class numeric_limits<int> : public _Num_base {
    public:
        static int min() {
            return INT_MIN;
        }
        static int max() {
            return INT_MAX;
        }
};

numeric_limits<int>, . float, char ..

, . _Ty 0. - ... . .

+2

.

numeric_limits<T> /. .

, min() max(). :

struct foo {
    int x;
    foo(int x) : x(x) {}
};

bool operator ==(foo const& a, foo const& b) { return a.x == b.x; }

assert(std::numeric_limits<foo>::min() == std::numeric_limits<foo>::max());

... , . , numeric_limits foo.

+6

, , , , , .

+2

, " " undefined. . , :

template<> class _CRTIMP2_PURE numeric_limits<char>
    : public _Num_int_base
    {   // limits for type char
public:
    typedef char _Ty;

    static _Ty (__CRTDECL min)() _THROW0()
        {   // return minimum value
        return (CHAR_MIN);
        }

    static _Ty (__CRTDECL max)() _THROW0()
        {   // return maximum value
        return (CHAR_MAX);
        }
// etc.

};

generic char, .

, :

int iMax = std::numeric_limits<char>::max() ;

it will use the specialized version of numeric_limits at compile time and thus put the value of CHAR_MAX in the iMax variable.

+1
source

Source: https://habr.com/ru/post/1745138/


All Articles