使用模板的条件typedef的更干净的替代方案

cleaner alternative for conditional typedef using templates

本文关键字:方案 typedef 条件      更新时间:2023-10-16

在玩一些模板时,为了删除代码中的一些宏,我使用了以下代码,

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函数,开销最小。

也许别名会对您有所帮助:

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;

请注意,我不确定这是否能解决你的问题,但如果你抱怨的是模板太长,那么以上技巧可能会让你知道如何缩短模板和清洁剂

如果你有C++14:,你可以使用_t版本

template<typename T, typename U>
using best = std::conditional_t<sizeof(T)==sizeof(void*),T,U>;

希望能有所帮助。

对于这个特定的任务,您似乎想要(大致):

typedef intptr_t Int;
typedef uintptr_t UInt;