使用模板的条件typedef的更干净的替代方案
cleaner alternative for conditional typedef using templates
在玩一些模板时,为了删除代码中的一些宏,我使用了以下代码,
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;
相关文章:
- C++:TypeDef使用元组
- 运行同一解决方案的另一个项目的项目
- Project Euler问题4的错误解决方案
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- visual c++,如何获取解决方案目录中的代码
- 为什么在使用typedef时类推导指南会失败
- 有没有办法在远程设备上打开和编辑visual Studio 2017解决方案
- C++Matching Brackets 2解决方案不起作用
- 在 ubuntu3 上C++ goto 定义有什么解决方案吗16.04?
- C++11 中不同类型的对象的 std::array 的替代方案
- 在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误
- 尝试根据类中 typedef 的存在来专门化模板函数
- 别名模板的专业化 C++11 中没有开销的最佳替代方案
- 如何重新定义MPI_FLOAT,MPI_DOUBLE以 typedef 的方式
- typedef 枚举和枚举类有什么区别?
- 使用模板的条件typedef的更干净的替代方案
- 使用强typedef作为Boost参数库的更轻量级的替代方案
- 虚拟typedef的替代方案