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

vav*_*ava 7 c++ 64-bit templates 32-bit

我有一个模板,我想专门研究两种int类型,其中一种是普通的int,另一种是intptr_t.在64位平台上,它们具有不同的大小,我可以轻松地做到这一点,但在32位上,两种类型都是相同的,编译器会抛出有关重新定义的错误.除了使用预处理器禁用其中一个定义外,我该怎么做才能解决它?

一些代码作为例子:

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(); }
Run Code Online (Sandbox Code Playgroud)

Ond*_*nde 2

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

template<typename T>
type * convert() { return getProperIntType(sizeof(T)); }

template<>
type * convert<void>() { return getProperVoidType(); }
Run Code Online (Sandbox Code Playgroud)