gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:39:20 25 4
gpt4 key购买 nike

我有一个模板,我想专注于两种 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(); }

最佳答案

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

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

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

关于c++ - 如何在 32 位和 64 位环境中使用 intptr_t 可靠地专门化模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2903716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com