C++中的Typeof()运算符

Typeof() operator in vc++

本文关键字:运算符 Typeof 中的 C++      更新时间:2023-10-16

我正在为正在进行的项目编写一些辅助函数。我一直想要一种类型的运算符。我知道它不存在于我当前的IDE(visualstudio'10)中,所以我试图为它编写一个实现。它应该是这样工作的:

auto var = new typeof(<expression>);

它应该只是一个基于表达式的编译时可检索类型,并且应该是可能的。C++在引入模板参数时使用此方法,例如:

template< typename A >
void foo(A unused) { 
/*  can be invoked like foo(5) with A = int     */
    typedef A type;
    type * used = new type;
}

所以我想我可以玩宏、类和模板。。像这样的东西:

#define typeof(expression)  (_type_creater().inducer(expression)::type)
template<typename T>
class _type_holder{
public:
    typedef T type;
};
class _type_creater{
public:
template< class B >
    _type_holder<B> inducer(B _temp) {
        /*  Here compiler induces the templated expression and creates a typename out of it.
            this we can use extract typename from _type_holder, except a instantiatet type apparantly
            doesn't have access to typedef'd typenames.
        */
        return _type_holder<B>();
    }
};

所以问题基本上是,这是非法的:

struct a
{
   typedef int type;
}
...
a mya;
new mya::type; //or mya.type

所以第一个问题是,为什么这是非法的?为什么不能从实例化类型中检索类型名?第二个问题,我能这样做吗?我试着寻找一个boosts TYPEOF,但没有太多意义,而且它似乎只是利用了VC编译器中的错误("//VC7.0特定的错误功能"、"//VC8.0特定的错误特性"、"//这使用了不错的VC6.5和VC7.1错误功能")。我运气不好吗?

对象不是作用域。作用域解析运算符(::)仅适用于作用域(类作用域、命名空间作用域、全局(命名空间)作用域)。我在对这个问题的评论中提供了一些补充信息作为理论。