vc ++中的Typeof()运算符

时间:2012-03-23 01:22:09

标签: c++ visual-studio typeof

我正在为正在进行的项目编写一些辅助函数。我一直想要一个typeof操作符。我知道它在我当前的IDE(visual studio '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

所以第一个问题是,为什么这是非法的?为什么不能从instantiatet类型中检索类型名? 第二个问题,我可以这样做吗?我试着看看增强版TYPEOF,但对它没有多大意义,似乎它只是利用VC编译器中的错误(“//VC7.0特定bugfeature”,“// VC8.0特定bugfeature”,“/ /这使用了漂亮的VC6.5和VC7.1 bugfeature“)。 我运气不好吗?

1 个答案:

答案 0 :(得分:0)

对象不是范围。范围解析运算符(::)仅适用于范围(类范围,命名空间范围,全局(命名空间)范围)。我在这个问题的评论中给出了一些额外的信息作为理论。

相关问题