【问题标题】:Typeof() operator in vc++vc++ 中的 typeof() 运算符
【发布时间】:2012-03-23 01:22:08
【问题描述】:

我正在为我正在进行的项目编写一些辅助函数。我一直想要一个 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

所以第一个问题是,为什么这是非法的?为什么不能从实例化类型中检索类型名? 第二个问题,我可以这样做吗?我试着寻找一个 boosts TYPEOF,但无法理解它,它似乎只是利用了 VC 编译器中的错误(“//VC7.0 特定错误功能”、“//VC8.0 特定错误功能”、“/ / 这使用了不错的 VC6.5 和 VC7.1 的 bugfeature")。 我倒霉了吗?

【问题讨论】:

  • "我一直想要一个 typeof 运算符。我知道它在我当前的 IDE (visual studio '10) 中不存在" 是的,它被称为decltype.
  • @ildjarn 我爱你,谢谢。不知道我怎么忽略了它。至于第一个问题,虽然...?
  • 我不知道你在寻找什么答案。语法是非法的——你想知道为什么它是非法的吗?我认为不属于 ISO C++ 委员会的任何人都无法合理地回答这个问题。
  • 在前面的例子中,做 a::type 是合法的,但 mya::type 不合法。是的,我想我想知道为什么,也许这背后有一个合乎逻辑的原因?
  • 也许吧,但我怀疑知道这个原因的人会在这里发帖。

标签: c++ visual-studio typeof


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-08
    • 2011-06-03
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    相关资源
    最近更新 更多