代码之家  ›  专栏  ›  技术社区  ›  niXman

如何获取变量的类型?

  •  0
  • niXman  · 技术社区  · 15 年前

    例子:

    template<typename T>
    struct type_of {
       typedef boost::mpl::if_<boost::is_pointer<T>,
       typename boost::remove_pointer<T>::type,
       T
       >::type type;
    };
    
    int main() {
       int* ip;
       type_of<ip>::type iv = 3; // error: 'ip' cannot appear in a constant-expression
    }
    

    2 回复  |  直到 14 年前
        1
  •  2
  •   GManNickG    15 年前

    你不能。可以使用编译器特定的扩展,也可以使用Boost的Typeof(它将编译器特定的行为隐藏在一致的接口后面)。

    在C++ 0x中,您可以使用 decltype decltype(ip) iv = 3; 如果编译器支持C++ 0x的这个方面,那么你就很幸运了。

        2
  •  2
  •   Alexandre C.    15 年前

    在当前的C++规范中,不能获得变量的类型,至少没有编译器特定的东西(但是尝试) boost::typeof 以透明的方式收集这些技巧)。

    type_of<int>::type int 原样 type_of<int*>::type .