获取类型名称或表达式的类型 [英] Getting the type of a typename or expression
问题描述
请考虑以下示例。我的代码中某处是一个名称 x
。我不知道 x
是类型还是对象(可能是两者)。有没有办法获取 x
的类型,即如果 x
是类型,还是 decltype(x)
是 x
是对象吗?
Consider the following example. Somewhere in my code is a name x
. I have no idea if x
is a type or an object (it could be both). Is there any way to get the type of x
, i.e., x
itself if x
is a type or decltype(x)
if x
is an object?
我尝试做一些琐碎的事情
I tried doing something as trivial as
decltype(int)
但这会产生错误,因为 int
不是表达式。有什么替代方法吗?
but this yields an error, since int
is not an expression. Is there any substitute way to do this?
我想要类似的东西:
typedef int l;
mydecltype(l) x; // int x;
mydecltype(x) y; // int y;
如何完成此操作?
推荐答案
namespace detail_typeOrName {
struct probe {
template <class T>
operator T() const;
};
template <class T>
T operator * (T const &, probe);
probe operator *(probe);
}
#define mydecltype(x) decltype((x) * detail_typeOrName::probe{})
在此代码中,(x)* detail_typeOrName :: probe {}
可以用两种方式解析:
In this code, (x) * detail_typeOrName::probe{}
can be parsed two ways:
- 如果
x
是变量,则为x
乘以probe
的实例。 - 如果
x
是一种类型,这是probe
被取消引用并转换为X
的实例。
- If
x
is a variable, this isx
multiplied by the instance ofprobe
. - If
x
is a type, this is the instance ofprobe
dereferenced and cast toX
.
通过仔细重载运算符,两种解释均有效,并且都返回我们要查找的类型。
By carefully overloading operators, both interpretations are made valid, and both return the type we seek.
这篇关于获取类型名称或表达式的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!