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

时间:2018-03-21 12:08:02

标签: c++ types enums return constexpr

我需要它用于我正在制作的套接字缓冲区(读取和写入...),这比其他任何东西都更加狡猾,所以我想知道是否有更好的方法来实现它目前的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);

感谢您的回复。

2 个答案:

答案 0 :(得分:3)

您可以使用良好的旧显式模板类专业化:

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

但我不认为这比传统方法更优越。

答案 1 :(得分:0)

基于@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因为它看起来并不好看。 再次感谢!