我需要它来做我正在做的套接字缓冲区(读和写...),这比其他任何东西都更有用,所以我想知道是否有一种更好的方法可以使用当前的c++功能/标准?我敢肯定。
enum e_Types
{
Type_64 ,
Type_32 ,
Type_16 ,
Type_8 ,
Type_ALL
};
template<e_Types Type> constexpr auto _GetVarType()
{
if constexpr( Type == Type_8 )
return ( unsigned char* ) 0;
if constexpr( Type == Type_16 )
return ( unsigned short* ) 0;
if constexpr( Type == Type_32 )
return ( unsigned long* ) 0;
if constexpr( Type == Type_64 )
return ( unsigned long long* ) 0;
}
#define GetVarType(type) decltype( _GetVarType<type>() )
例:
GetVarType( Type_64 ) p64 = malloc(0x1000);
感谢您的答复。
最佳答案
您可以使用良好的旧的显式模板类特化:
template <e_Types X> struct type_of;
template <> struct type_of<Type_64> { using type = unsigned long long; };
template <> struct type_of<Type_32> { using type = unsigned long; };
template <> struct type_of<Type_16> { using type = unsigned short; };
template <> struct type_of<Type_8> { using type = unsigned char; };
template <e_Types X>
using type_of_t = typename type_of<X>::type;
用法:
type_of_t<Type_64>* p64 = malloc(0x1000);
如果您想沿着基于
constexpr
的路线走,您可以执行以下操作:template <typename T>
struct type_wrapper
{
using type = T;
};
template <typename T>
inline constexpr type_wrapper<T> t{};
template <e_Types X> inline constexpr auto type_of = t<void>;
template <> inline constexpr auto type_of<Type_64> = t<unsigned long long>;
template <> inline constexpr auto type_of<Type_32> = t<unsigned long>;
template <> inline constexpr auto type_of<Type_16> = t<unsigned short>;
template <> inline constexpr auto type_of<Type_8> = t<unsigned char>;
用法:
typename decltype(type_of<Type_64>)::type* p64 = malloc(0x1000);
但是我发现这并不优于传统方法。
关于c++ - 沿枚举C返回变量类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49405975/