沿枚举 c++ 返回变量类型



我需要它来制作我正在制作的套接字缓冲区(读取和写入...(,这比其他任何事情都更像是一个技巧,所以我想知道是否有更好的方法可以使用当前的 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);

但我不觉得这优于更传统的方法。

基于@liliscent和@VittorioRomeo回复/评论,我最终这样做了:

template <typename T>
struct Type_Wrapper
{
    using Type = T;
};
template <typename T>
inline constexpr Type_Wrapper<T> _Type{};
template <e_Types Type> inline constexpr auto _GetVarType()
{
    if constexpr( Type == Type_8 )
        return _Type<Byte>;
    else if constexpr( Type == Type_16 )
        return _Type<Word>;
    else if constexpr( Type == Type_32 )
        return _Type<HEX32>;
    else if constexpr( Type == Type_64 )
        return _Type<HEX64>;
    else if constexpr( Type == Type_Pointer )
        return _Type<Pointer>;
    else if constexpr( Type == Type_Size )
        return _Type<size_t>;
    else if constexpr( Type == Type_Array )
        return _Type<Bytes>;
    else
        return _Type<void>;
};
template<e_Types _Type>
using GetVarType_t = typename decltype( _GetVarType<_Type>() );

GetVarType_t< Type_64 >::Type Ok = 0;

现在很好,我想摆脱那些 0 因为看起来不太好。再次感谢!

最新更新