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

发布于 2024-09-02 10:31:16 字数 640 浏览 5 评论 0原文

我有一个模板,我想专门使用两种 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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伴我心暖 2024-09-09 10:31:16

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

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

template<>
type * convert<void>() { return getProperVoidType(); }

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:

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

template<>
type * convert<void>() { return getProperVoidType(); }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文