Bhi*_*fer 2 c++ macros templates function-templates
我想请教您关于功能模板的建议.我有一个功能,可以将一些数据添加到缓冲区.但我还需要将有关数据类型的信息添加到缓冲区中.数据类型是以下枚举:
enum ParameterType
{
UINT,
FLOAT,
DOUBLE
};
Run Code Online (Sandbox Code Playgroud)
我需要从这样的函数创建一个函数模板:
void SomeBuffer::append( double par )
{
appendType( DOUBLE );
memcpy( pStr + _length, &par, sizeof( double ) );
_length += sizeof( double );
appendType( DOUBLE );
}
Run Code Online (Sandbox Code Playgroud)
你能否告诉我如何根据参数类型从ParameterType传递appendType()的值.
template<class T>
void SomeBuffer::append( T par )
{
appendType( ??? );
memcpy( pStr + _length, &par, sizeof( T ) );
_length += sizeof( T );
appendType( ??? );
}
Run Code Online (Sandbox Code Playgroud)
我尝试用一些宏来做但没有成功.非常感谢您的任何建议.
您可以通过引入一个额外的类模板来执行您想要的操作,该模板将类型映射到您需要的枚举常量,如以下示例所示(为简洁起见,不使用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);
}
Run Code Online (Sandbox Code Playgroud)
由于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)
Run Code Online (Sandbox Code Playgroud)