【发布时间】:2015-04-26 06:45:41
【问题描述】:
所以我有这个非常丑陋的代码:
template <typename T>
std::conditional_t<sizeof(T) == sizeof(char),
char,
conditional_t<sizeof(T) == sizeof(short),
short,
conditional_t<sizeof(T) == sizeof(long),
long,
enable_if_t<sizeof(T) == sizeof(long long),
long long>>>> foo(T bar){return reinterpret_cast<decltype(foo(bar))>(bar);}
我正在使用嵌套的conditional_ts 来进行各种案例陈述。有没有什么可以更优雅地完成此任务,还是我需要编写自己的模板化案例陈述?
注意:我实际上知道reinterpret_cast 的这种使用是不好的:Why Doesn't reinterpret_cast Force copy_n for Casts between Same-Sized Types?
【问题讨论】:
-
这段代码试图达到什么目的?
-
你可以为 char,short,int, long long 做一个模板...
-
为什么这感觉像是你的依赖类型编程语言?
-
@Slava Lol,我试图找到一种方法来清理这个:stackoverflow.com/a/28634468/2642059
-
@Slava:将任何类型的对象转换为包含相同字节值的相同大小(如果存在)的基本类型。
标签: c++ templates conditional case-statement nested-if