gpt4 book ai didi

c++ - 使用模板的条件 typedef 的更清洁替代方案

转载 作者:搜寻专家 更新时间:2023-10-31 00:33:04 26 4
gpt4 key购买 nike

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

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>;

希望对您有所帮助。

关于c++ - 使用模板的条件 typedef 的更清洁替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29805114/

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