tags:

views:

129

answers:

4

Is it possible to return type of an object? For example I would like to have construct like this:

//pseudocode
    template<class T>
    void f(int value)
    {
    //depends on type T different action can be taken
    }

template<class T>
type getType(T obj)
{
return (type of obj);
}

and then in main:

f<getType(Object)>(value);  
A: 

In C++0x there is decltype and auto that can be used

David
+5  A: 

Yes in some sense, but you need to move T into a parameter. This is the conditional trick explored by Eric Niebler and explained here.

template<typename T>
struct id { typedef T type; };

template<typename T>
id<T> make_id(T) { return id<T>(); }

struct get_type {
  template<typename T>
  operator id<T>() { return id<T>(); }
};

#define pass_type(E) (true ? get_type() : make_id((E)))

pass_type(expression) yields an id<T> object such that T is the cv-unqualified type of that expression. So you can do

template<class T>
void f(int value, id<T>)
{
    // Now go on as usual on T
}

f(value, pass_type(Object));
Johannes Schaub - litb
That's awesome.
GMan
A: 

In template metaprogramming, this is normally done via class templates.

template <typename T>
struct GetType
{
    typedef T type;  // usually it's something more complex
};

// example: partial specialization is used to compute element type of some container template
template <typename T>
struct GetType< MyContainerType<T> >
{
    typedef T type;
};


.........................

// and now you use it:
f<GetType<Object>::type>(value);  

Here, struct GetType<T> can be thought of as a (meta)function taking one type argument and returning one type value.

atzz
A: 

I think that you just need to use function template specialization:

template<>
void f(int value)
{
  .. operations when an int
}


template<>
void f(char value)
{
  .. operations when a char
}


template<>
void f(double value)
{
  .. operations when a double
}


template<class T>
void f(T value)
{
  .. operations when a T (not int, char or double)
}
JBRWilkinson
@JBRWilkinson I think that's it. I'll check it tommorow and I let you know. Thanks for your answer.
There is nothing we can do
How is it different from function overload?
atzz
Since it is a simple function, I guess it isn't really different, so just function overloading would suffice, but the final catch-all template would still be required.
JBRWilkinson