是否可以返回一个对象的类型?例如我想有这样的构造:
//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);
}
然后在主要部分:
f<getType(Object)>(value);
最佳答案
从某种意义上说是的,但你需要移动T
成一个参数。这是 Eric Niebler 探索的条件技巧并解释了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)
产生 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));
关于c++ - 返回对象的类型;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3846565/