获取类型名称或表达式的类型 [英] Getting the type of a typename or expression

查看:72
本文介绍了获取类型名称或表达式的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例。我的代码中某处是一个名称 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 is x multiplied by the instance of probe.
  • If x is a type, this is the instance of probe dereferenced and cast to X.

通过仔细重载运算符,两种解释均有效,并且都返回我们要查找的类型。

By carefully overloading operators, both interpretations are made valid, and both return the type we seek.

在Coliru上直播

这篇关于获取类型名称或表达式的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆