C ++模板专业化 - 非类型模板参数的非法类型' __ formal

时间:2014-06-06 14:39:57

标签: 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;
}

我在VS2005上收到此错误:

Error   1   error C2993: 'std::string' : illegal type for non-type template parameter '__formal'    c:\dev\floatinglicences\common\common.h 50

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

你会帮帮我吗?谢谢:))

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:4)

专业化应该是:

template<>
std::string read< std::string >( blah blah blah)

答案 2 :(得分:3)

显式专业化如下所示:

template <>
std::string read<std::string>( const std::vector< byte > & bytes, uint index )
{
    // ...
}

此处第一个<>是模板参数集。没有,因为您指定的是精确的函数类型,而不是另一个模板。第二个<>是模板参数,指定要定义的模板特化。

请注意,显式特化的定义属于源文件,而不是头文件。除非您添加inline

答案 3 :(得分:2)

更改自:

template< std::string >
std::string read( const std::vector< byte > & bytes, uint index ) 

到此:

template<>
std::string read< std::string >( const std::vector< byte > & bytes, uint index ) 
相关问题