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

如何在32位和64位环境中使用intptr\t可靠地专门化模板?

  •  7
  • vava  · 技术社区  · 16 年前

    我有一个模板,我想专门处理两个int类型,其中一个是纯旧的 int 另一个是 intptr_t

    以下是一些代码示例:

    template<typename T>
    type * convert();
    
    template<>
    type * convert<int>() { return getProperIntType(sizeof(int)); }
    
    template<>
    type * convert<intptr_t>() { return getProperIntType(sizeof(intptr_t)); }
    
    //this template can be specialized with non-integral types as well, 
    // so I can't just use sizeof() as template parameter.
    template<>
    type * convert<void>() { return getProperVoidType(); }
    
    1 回复  |  直到 16 年前
        1
  •  2
  •   Ondergetekende    16 年前

    您试图实现的基本上是不可能的:intptr_t是32位系统上int的typedef,因此编译器无法区分它们。但是,您的示例可以通过专门化void案例来解决:

    template<typename T>
    type * convert() { return getProperIntType(sizeof(T)); }
    
    template<>
    type * convert<void>() { return getProperVoidType(); }
    
    推荐文章