【问题标题】:C++ Template specialisation - illegal type for non-type template parameter '__formalC++ 模板特化 - 非类型模板参数 '__formal 的非法类型
【发布时间】: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


【解决方案1】:

专业化如下所示:

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

【讨论】:

    【解决方案2】:

    专业化应该是:

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

    【讨论】:

      【解决方案3】:

      显式特化如下所示:

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

      这里第一个&lt;&gt; 是模板参数集。没有,因为您指定的是确切的函数类型,而不是另一个模板。第二个&lt;&gt; 是模板参数,指定正在定义的模板特化。

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

      【讨论】:

      • 感谢关于内联的说明!
      【解决方案4】:

      更改自:

      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 ) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-16
        • 2021-03-18
        • 1970-01-01
        • 1970-01-01
        • 2017-07-18
        相关资源
        最近更新 更多