在玩一些模板时,为了删除代码中的一些宏,我得到了以下代码,
typedef std::conditional<sizeof(int) == sizeof(void*),
int,
std::conditional<sizeof(long int) == sizeof(void*),
long int,
std::enable_if<sizeof(long long int) == sizeof(void*), long long int>::type
>::type
>::type Int;
typedef std::conditional<sizeof(unsigned int) == sizeof(Int),
unsigned int,
std::conditional<sizeof(unsigned long int) == sizeof(Int),
unsigned long int,
std::enable_if<sizeof(unsigned long long int) == sizeof(Int), unsigned long long int>::type
>::type
>::type UInt;
尝试更换时,
#if sizeof(int) == sizeof(void*)
typedef int Int;
typedef unsigned int UInt;
#elif sizeof(long int) == sizeof(void*)
typedef long int Int;
typedef unsigned long int UInt;
#elif sizeof(long long int) == sizeof(void*)
typedef long long int Int;
typedef unsigned long long int UInt;
#else
#error
#endif
您能想到使用模板的更清洁,更短的替代方案吗?或者使用模板替换每个可能的宏只是一个坏主意。
顺便说一下,该代码用于将整数值传递给只接受void*
的某些C函数,而开销最小。
答案 0 :(得分:3)
也许别名可以帮到你:
using Int = best<int,best<long int,long long>>;
using UInt = best<unsigned int,best<unsigned long int,unsigned long long int>>;
其中best
是模板别名,定义为:
template<typename T, typename U>
using best = typename std::conditional<sizeof(T)==sizeof(void*),T,U>::type;
请注意,我不确定这是否能解决您的问题,但如果您的抱怨是关于冗长的模板,那么上述技巧可能会让您对如何缩短它有所了解 - and cleaner < / em>的
如果你有C ++ 14,可以使用_t
版本:
template<typename T, typename U>
using best = std::conditional_t<sizeof(T)==sizeof(void*),T,U>;
希望有所帮助。
答案 1 :(得分:2)
对于这项特殊任务,您似乎想要(大致):
typedef intptr_t Int;
typedef uintptr_t UInt;