gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:29:43 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com