Returning a type of an object;
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);
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));
In C++0x there is decltype and auto that can be used
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.
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)
}
精彩评论