开发者

How to reliably specialize template with intptr_t in 32 and 64 bit environments?

开发者 https://www.devze.com 2022-12-31 07:15 出处:网络
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 plat开发者_Python百科form they have different sizes and I can do that with e

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 plat开发者_Python百科form 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(); }


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(); }
0

精彩评论

暂无评论...
验证码 换一张
取 消