Using numeric_limits::max() in constant expressions

前端 未结 5 860
無奈伤痛
無奈伤痛 2020-12-10 11:04

I would like to define inside a class a constant which value is the maximum possible int. Something like this:

class A
{
    ...
    static const int ERROR_V         


        
5条回答
  •  清歌不尽
    2020-12-10 11:29

    • I will try to answer you as much as I understood from your question:

    1- If you want a static const int in your program to be initialized with a function:

    int Data()
    {
     return rand();
    }
    
    class A
    {
    public :
        static const int ee;
    };
    const int A::ee=Data();
    

    This works on VS 2008

    2- If you want to get max and min number for a given data type, then use these definitions INT_MAX, INT_MIN, LONG_MAX and so on..

    3- If however you need to use these wrt template type, then hard code the templates yourself

    template<>
    int MaxData()
    {
     return INT_MAX;
    }
    

    and

    template<>
    long MaxData()
    {
     return LONG_MAX ;
    }
    

    and call them like this

    int y=MaxData();
    

    4- and if you are only dealing with binary represented types only, then use this:

    template 
    T MaxData(){
        return ~(1<<((sizeof(T)*8)-1));
    }
    

    and this

    template 
    T MinData(){
        return (1<<((sizeof(T)*8)-1));
    }
    

    Hope this can help you..

提交回复
热议问题