Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

types

typeof

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.

like image 820
plong Avatar asked Oct 16 '09 17:10

plong


2 Answers

template<typename T>
T get_lim( const T & x)
{
 return numeric_limits<T>::max();
}

the good thing is that you can use it without explicitly specifying T:

size_t l = get_lim(34);

like image 82
alexkr Avatar answered Sep 17 '22 05:09

alexkr


Just FWIW, C++ 0x will also have decltype, which is nearly the same as typeof. They picked a new name primarily because the semantics are different in one case. The existing implementation of typeof (gcc) drops references from types, so typeof(int &) == int. The standard requires that decltype(int &) == int&. This doesn't matter very often, but they decided to use a different name to prevent any silent changes to existing code.

like image 23
Jerry Coffin Avatar answered Sep 20 '22 05:09

Jerry Coffin