【发布时间】:2014-06-06 14:39:57
【问题描述】:
我需要解析一个自定义协议的帧,这些帧可以包含各种大小的整数(uint8_t、uint16_t、uint32_t 等)和以长度为前缀的字符字符串(uint16_t)。
我想编写一个模板函数来从字节向量中读取这些值,以使语法更具可读性。这是我的功能:
template< typename type >
type read( const std::vector< byte > & bytes, uint index )
{
if( index + sizeof( type ) > bytes.size() )
{
throw exception( "read() - Out of range." );
}
type val;
memcpy( & val, & bytes[ index ], sizeof( type ) );
return val;
}
template< std::string >
std::string read( const std::vector< byte > & bytes, uint index ) // ERROR HERE
{
if( index + sizeof( type ) > bytes.size() )
{
throw exception( "read() - Out of range." );
}
uint16_t length = read< uint16_t >( bytes, 0 );
std::string str( length, '\0' );
for( uint16_t i = 0; i < length; ++i )
{
str[i] = read< char >( bytes, index + i );
}
return str;
}
我在 VS2005 上收到此错误:
Error 1 error C2993: 'std::string' : illegal type for non-type template parameter '__formal' c:\dev\floatinglicences\common\common.h 50
我不是模板专家。这是我第一次需要尝试进行模板专业化,所以我的语法可能是错误的。
你会帮助我吗?谢谢你:)
【问题讨论】:
-
一个人故意不做他应该做的事或根本没有想到的时候是不礼貌的吗?
-
我会这么说。这是你的听众缺乏思考,只考虑你自己的问题。不过,也许它比“不礼貌”更“不体谅”,请自行选择。无论如何,吸取教训,并感谢您的快速响应。
-
好的,谢谢大家的帮助。我会选择最快的答案,因为它们都是一样的:)
-
欢迎接受新人或声誉较低的人的回答。我认为任何高级代表都没有太多用处,这对年轻人来说是一种被接受的灵感。
-
@KerrekSB 是的。我还有一个问题,如果可以的话。如果我想专门处理我的函数来处理 basic_string
而不是 string 怎么办? :)
标签: c++ templates template-specialization