所以我有这个非常难看的代码:
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);}
Run Code Online (Sandbox Code Playgroud)
我正在使用嵌套的conditional_ts来创建一个case语句.有什么东西可以更优雅地完成这个或者我需要做出我自己的模板化案例陈述吗?
注意:我实际上意识到这种用法reinterpret_cast很糟糕:为什么不为同尺寸类型之间的强制转换重新解释强制copy_n?
我想把一个堆栈变量和reinterpret cast它变成一个大小相同的无符号整数类型.例如,我可能想要获取double值并将其转换为a uint64_t,并且不会修改位.我想以通用的方式做到这一点.
如果我正在处理指针,我会使用reinterpret_cast<uint64_t*>(double_ptr).
我提出了一个解决方案,它使用了一个肮脏的黑客reinterpret_cast,并且是有效的,但它需要相当多的元编程来获得一个相当简单的结果.
问题是:有更好的方法吗?我确信有,并且我正在使这比需要更复杂.
我确实考虑过使用类型T和尺寸合适的模板化联合int_t,但这看起来甚至更黑,并且似乎与未定义的行为一起玩.
编辑我理解标准没有指定double应该是64位,如注释中所指出的那样.但是使用通用方法,我将能够获得与double相同大小的无符号整数类型,无论大小如此.
#include <iostream>
template <typename T, std::size_t S>
struct helper {};
template <typename T>
struct helper<T, 1> {
using type = uint8_t;
};
template <typename T>
struct helper<T, 2> {
using type = uint16_t;
};
template <typename T>
struct helper<T, 4> {
using type = uint32_t;
};
template <typename T>
struct helper<T, 8> {
using type = uint64_t; …Run Code Online (Sandbox Code Playgroud) Mooing Duck 在这里发表评论"一个函数不能返回多个类型.但是,你可以专门化或委托重载,这很好."
我开始考虑这个问题,我想弄清楚,这个法律代码是怎样的:
template <typename T>
T initialize(){ return T(13); }
Run Code Online (Sandbox Code Playgroud)
通话时:
auto foo = initialize<int>();
auto bar = initialize<float>();
Run Code Online (Sandbox Code Playgroud)
这不会转换为仅由return-type重载的2个同名函数吗?
c++ ×3
templates ×2
c++11 ×1
casting ×1
conditional ×1
nested-if ×1
overloading ×1
return-type ×1
types ×1