如何在 32 位和 64 位环境中使用 intptr_t 可靠地专门化模板?
我有一个模板,我想专门使用两种 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(); }
I have a template I want to specialize with two int types, one of them plain old int
and another one is intptr_t
. On 64 bit platform they have different sizes and I can do that with ease but on 32 bit both types are the same and compiler throws an error about redefinition. What can I do to fix it except for disabling one of definitions off with preprocessor?
Some code as an example:
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(); }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您想要实现的目标基本上是不可能的:intptr_t 是 32 位系统上 int 的 typedef,因此编译器无法区分它们。但是,您的示例可以通过专门化 void 情况来解决:
What you're trying to achieve is fundamentally impossible: intptr_t is a typedef for int on 32 bit systems, so the compiler can't distinguish them. However, your example could be solved by just specializing the void case: