gpt4 book ai didi

c++ - 判断函数模板中的类型

转载 作者:太空狗 更新时间:2023-10-29 23:31:33 29 4
gpt4 key购买 nike

我想向您请教有关函数模板的建议。我有一个将一些数据添加到缓冲区的函数。但我还需要将有关数据类型的信息添加到缓冲区中。数据类型是以下枚举:

enum ParameterType
{
UINT,
FLOAT,
DOUBLE
};

我需要从这样的函数创建一个函数模板:

void SomeBuffer::append( double par )
{
appendType( DOUBLE );
memcpy( pStr + _length, &par, sizeof( double ) );
_length += sizeof( double );
appendType( DOUBLE );
}

能否请您告诉我如何根据参数类型从 ParameterType 向 appendType() 传递值。

template<class T>
void SomeBuffer::append( T par )
{
appendType( ??? );
memcpy( pStr + _length, &par, sizeof( T ) );
_length += sizeof( T );
appendType( ??? );
}

我尝试通过一些宏来实现,但没有成功。非常感谢您的任何建议。

最佳答案

您可以通过引入一个额外的类模板来完成您想要的操作,该模板将类型映射到您需要的枚举常量,如以下示例所示(为简洁起见,没有 FLOAT):

enum ParameterType
{
UINT,
DOUBLE
};

template <typename T>
struct GetTypeCode;

template <>
struct GetTypeCode<double>
{
static const ParameterType Value = DOUBLE;
};

template <>
struct GetTypeCode<unsigned>
{
static const ParameterType Value = UINT;
};

template <typename T>
void SomeBuffer::append(T par)
{
appendType(GetTypeCode<T>::Value);
memcpy(pStr + _length, &par, sizeof(T));
_length += sizeof(T);
appendType(GetTypeCode<T>::Value);
}

由于 GetTypeCode 的特化几乎相同,您可以引入一个宏来定义它们,例如

#define MAP_TYPE_CODE(Type, ID) \
template <> \
struct GetTypeCode<Type> \
{ \
static const ParameterType Value = ID; \
};

MAP_TYPE_CODE(double, DOUBLE)
MAP_TYPE_CODE(unsigned, UINT)

关于c++ - 判断函数模板中的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4051974/

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