函数模板中类型的确定
我想请教一下关于函数模板的建议。我有一个函数可以将一些数据添加到缓冲区中。但我还需要将有关数据类型的信息添加到缓冲区中。数据类型是以下枚举:
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( ??? );
}
我尝试通过一些宏来做到这一点,但没有成功。非常感谢您的任何建议。
I would like to ask you for an advice about function template. I have a function that adds some data into buffer. But I need also to add an information about data type into the buffer. The type of data is a following enum:
enum ParameterType
{
UINT,
FLOAT,
DOUBLE
};
And I need to create a function template from function like this:
void SomeBuffer::append( double par )
{
appendType( DOUBLE );
memcpy( pStr + _length, &par, sizeof( double ) );
_length += sizeof( double );
appendType( DOUBLE );
}
Could you please advice me how to pass a value from ParameterType for appendType() depending on type of parameter.
template<class T>
void SomeBuffer::append( T par )
{
appendType( ??? );
memcpy( pStr + _length, &par, sizeof( T ) );
_length += sizeof( T );
appendType( ??? );
}
I tried to do it by some macros but without success. Thank you very much for any advice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过引入一个附加的类模板来完成您想要的操作,该模板会将类型映射到您需要的枚举常量,如下例所示(为了简洁起见,没有 FLOAT):
由于 GetTypeCode 的特化几乎相同,因此您可以引入一个宏定义它们,例如
You can do what you want by introducing an additional class template that will map the type to the enumeration constant that you need as in the following example (without FLOAT for brevity):
Since specializations of GetTypeCode will be almost identical you may introduce a macro for defining them, e.g.
然后像这样使用它:
您还可以将其与 @vitaut 的想法结合起来,即单独获取类型代码并将其传递给
appendType
。编辑:感谢@Johannes 的
identity
建议。Then use it like so:
You could also combine this with @vitaut's idea of getting the type code separately, and passing it to
appendType
.EDIT: Thanks to @Johannes for the
identity<T>
suggestion.与 Marcelo Cantos 给出的方法不同的方法是创建一个元函数:
然后使用它来解析枚举值:
特征的实际定义可以在宏中定义:
A different approach to that given by Marcelo Cantos would be creating a metafunction:
And then using that to resolve the enumerated value:
The actual definition of the traits can be defined in a macro: