C++模板特化 - 非类型模板参数'__formal的非法类型

Vir*_*721 1 c++ templates template-specialization

我需要解析一个自定义协议的框架,它可以包含各种大小的整数(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;
}
Run Code Online (Sandbox Code Playgroud)

我在VS2005上收到此错误:

Error   1   error C2993: 'std::string' : illegal type for non-type template parameter '__formal'    c:\dev\floatinglicences\common\common.h 50
Run Code Online (Sandbox Code Playgroud)

我不是模板专家.这是我第一次尝试进行模板专业化,所以我的语法可能是错误的.

你会帮我吗 ?谢谢 :)

Ker*_* SB 8

专业化看起来像这样:

template <typename T>
void foo(A x, B y, C z);                    // primary template

template <>
void foo<std::string> foo(A x, B y, C z);   // specialized for T = std::string
Run Code Online (Sandbox Code Playgroud)