是否可以返回对象的类型?例如,我想有这样的结构:
//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);
}
Run Code Online (Sandbox Code Playgroud)
然后在主要:
f<getType(Object)>(value);
Run Code Online (Sandbox Code Playgroud)
在某种意义上是肯定的,但您需要T进入参数.这是Eric Niebler探索的条件技巧并在此解释.
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)))
Run Code Online (Sandbox Code Playgroud)
pass_type(expression)产生一个id<T>对象,这T是该表达式的cv非限定类型.所以你可以做到
template<class T>
void f(int value, id<T>)
{
// Now go on as usual on T
}
f(value, pass_type(Object));
Run Code Online (Sandbox Code Playgroud)