获取typename或表达式的类型

Mat*_*nti 8 c++ decltype

请考虑以下示例.在我的代码中的某个地方是一个名字x.我不知道x是类型还是对象(它可能都是).有没有办法获得类型x,即,x如果x是一个类型或decltype(x)如果x是一个对象本身?

我尝试做一些像小事一样的事情

decltype(int)
Run Code Online (Sandbox Code Playgroud)

但这会产生错误,因为int它不是表达式.有没有替代方法来做到这一点?

我想要像:

typedef int l;
mydecltype(l) x; // int x;
mydecltype(x) y; // int y;
Run Code Online (Sandbox Code Playgroud)

我怎么能这样做?

Que*_*tin 23

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{})
Run Code Online (Sandbox Code Playgroud)

在这段代码中,(x) * detail_typeOrName::probe{}可以解析两种方式:

  • 如果x是变量,则x乘以实例probe.
  • 如果x是类型,则这是probe取消引用和强制转换的实例X.

通过仔细地重载操作符,两种解释都是有效的,并且都返回我们寻求的类型.

住在Coliru