[C++] typeof ?

Started by
3 comments, last by ColeFreeman 16 years, 1 month ago
Hi. I cannot find functionality for deducing compile time type from an arbitrary variable, typeof is removed completely?. (VS2005 unmanaged c++) BOOST_TYPEOF needs registering of user types/templates beforehand, which is not possible in many cases. So what I need to do in compiletime is: AnyType a; typeof(a) b;//AnyType b It will be used together with macros to simplify some heavily templated programming interfaces I have that are quite tedious to use at the moment. Any info is greatly appreciated. Thank you.
Advertisement
There's nothing in that form you can do. Depending on the context, there may be a different way, involving templates. See, for example, the implementation of std::swap. Disregarding exception safety, it looks something like this:

template<typename T>void swap(T & a, T & b){    T temp = a;    a = b;    b = temp;}int foo = 3;int bar = 4;swap(foo, bar);


Note that "temp" has the same type as "a" and "b".
There is no standard means of obtaining the type of a variable, although there have been proposals to add this to the next standard (C++0x).

The only means you have at your disposal, when manipulating a variable of unknown type, is to place yourself within a context where that type is obvious:
UnknownType a;typeof(a) b; // Obviously does not workfrobnicate(a,b);


Becomes:
template<typename T> impl(T & a){  T b;  frobnicate(a, b);}UnknownType a;impl(a);
As has been said templates are the key here; yet if you were using g++ then typeof could be used.
Thanks for the quick replies.

Sticking to the global context for a while longer then, thx again.

This topic is closed to new replies.

Advertisement