Search code examples
c++typestypeof

C++ Get object type at compile time, e.g., numeric_limits<typeof<a>>::max()?


Given int a;, I know that the following returns the largest value that a can hold.

numeric_limits<int>::max()

However, I'd like to get this same information without knowing that a is an int. I'd like to do something like this:

numeric_limits<typeof<a>>::max()
Not with this exact syntax, but is this even possible using ISO C++?


Thanks, all. Aurélien Vallée's type_of() comes closest, but I'd rather not add anything extra to our codebase. Since we already use Boost, Éric Malenfant's reference to Boost.Typeof led me to use

numeric_limits<BOOST_TYPEOF(m_focusspeed)>::max()

I'd never used it before. Again, thanks for so many well-informed responses.


Solution

  • numeric_limits is what is known as a type trait. It stores information relative to a type, in an unobtrusive way.

    Concerning your question, you can just define a template function that will determine the type of the variable for you.

    template <typename T>
    T valued_max( const T& v )
    {
      return numeric_limits<T>::max();
    };
    
    template <typename T>
    T valued_min( const T& v )
    {
      return numeric_limits<T>::min();
    };
    

    or just create a small type returning structure:

    template <typename T>
    struct TypeOf
    {
      typedef T type;
    };
    
    template <typename T>
    TypeOf<T> type_of( const T& v )
    {
      return TypeOf<T>();
    }
    
    int a;
    numeric_limits<type_of(a)::type>::max();