When typeof operator is useful?
I have read about typeof operator some days ago and wondering when it will be really useful.
I found an use of it today. typeof operator accepts an argument and it returns its type as return value. Ofcourse its static type of value.
So we can write expressions like the following with typeof operator.
int x = 10 ;
typeof(x) x1 = x ;
What's the big deal in it? When we know type of x what's there to declare another variable of same type. But it is really useful when you can access a typedef which you know is a pointer or reference and want to use its real type.
For ex. assume that there is a class CElement. Then you create a container C of CElement *. You pass C to a generic function which is capable working on any container of CElement *. Then question is how can access type CElement in that function?
class CElement
{
} ;
vector
createAnElement(v) ;
template
void createAnElement(const T& v)
{
*(T::value_type) element ; // Won't work gives an error
}
In such a case our typeof operator is useful.
template
void createAnElement(const T& v)
{
extern typename T::value_type pointer_type ;
typedef typeof(*pointer_type) ELEMENT_TYPE ;
ELEMENT_TYPE element ;
}

0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home