Sign in to follow this  
ColeFreeman

[C++] typeof ?

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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".

Share this post


Link to post
Share on other sites
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 work
frobnicate(a,b);


Becomes:
template<typename T> impl(T & a)
{
T b;
frobnicate(a, b);
}

UnknownType a;
impl(a);

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this