【问题标题】:c++ function template specialisationc++ 函数模板特化
【发布时间】:2011-10-12 10:45:05
【问题描述】:

鉴于此代码:

class X
{
public:
    template< typename T >
    void func( const T & v );
};

template<>
void X::func< int >( const int & v )
{
}

template<>
void X::func< char * >( const char * & v )       // 16
{
}

当我编译它时,我得到以下错误。

test.cpp:16: error: template-id 'func<char*>' for 'void X::func(const char*&)' does not match any template declaration

任何人都可以对此有所了解吗?

【问题讨论】:

  • 如果你不打算实现template&lt;typename T&gt; void X::func (const T &amp; t) { ... },你可以只使用为intchar*参数重载的成员函数。

标签: c++ templates template-specialization


【解决方案1】:

如果您更改声明:

template<> void X::func< char * >( const char * & v )

到:

template<> void X::func< char * >( char * const & v )

这将完全正常。为什么会发生?因为虽然const sometype 完全可以接受,但它只是sometype const 的替代符号。因此,您的 const 修饰符不应用于基本类型 (char),而是应用于指针,使“指向非常量字符的常量指针”成为有效类型。如果这不是您想要的,则必须更正您的基本模板。

最后,这里有一些关于why overloading templates is generally better than specializing them 的有趣读物。

【讨论】:

  • 哇,真的很棒的描述。
【解决方案2】:

您遇到此错误的原因是因为您在类型前写了const。虽然这是常见的做法,但不利于理解 const/volatile-qualifiers (cv-qualifier) 的工作原理。

在这种情况下,const T Tchar* 并不意味着 const char*。它的意思是char* const,因为Tchar*,无论你把const 放在T 的哪一边,它的行为都好像constT 的右边,即指针本身那将是 const 而不是指向的类型。

如果您规定始终将constvolatile 放在类型的右侧,则很容易避免这种类型的混淆。例如,当Tchar*char* const 时,它可以直接在心理上扩展T const

这就是在 boost 源中你在类型之后而不是之前看到 cv-qualifiers 的原因。

【讨论】:

    【解决方案3】:

    const移动到&amp;之前

    template<> 
    void X::func< char * >( char * const & v ) 
    { 
    } 
    

    【讨论】:

      猜你喜欢
      • 2011-10-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-27
      • 1970-01-01
      • 2016-12-04
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多