c++函数模板特化
给出这段代码:
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
任何人都可以阐明这一点吗?
Given this code:
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
{
}
When I compile it I get the following error.
test.cpp:16: error: template-id 'func<char*>' for 'void X::func(const char*&)' does not match any template declaration
Can anyone shed any light on this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您将声明:更改
为:,
这将工作得很好。为什么会发生这种情况?因为虽然
const sometype
是完全可以接受的,但它只是sometype const
的替代表示法。因此,您的 const 修饰符不会应用于基本类型 (char
),而是应用于指针,从而使“指向非常量 char 的常量指针”成为有效类型。如果这不是您想要的,则必须更正您的基本模板。最后,这里有一些关于为什么重载模板通常比专门化它们更好的有趣读物。
If you change the declaration:
to:
This would work perfectly fine. Why does it happen? Because while
const sometype
is perfectly acceptable, it's only an alternative notation forsometype const
. So, your const modifier is not applied to the basic type (char
), but to the pointer, making "constant pointer to non-constant char" a valid type. If that's not what you want, you'll have to correct your basic template.Finally, here's some interesting reading for you about why overloading templates is generally better than specializing them.
您遇到此错误的原因是因为您在类型之前编写了
const
。尽管这是常见的做法,但它不利于理解 const/易失性限定符 (cv-qualifier) 的工作原理。在这种情况下,当
T
为char*
时,const T
并不意味着const char*
。它的意思是char* const
因为T
是char*
并且无论您将T
放在哪一边>const 它的行为就好像const
位于T
的右侧,也就是说,指针本身将是 const,而不是指向的类型。如果您制定一条规则,始终将
const
或volatile
放在类型的右侧,则很容易避免这种类型的混淆。例如,当T
为char*
到char* const
时,可以在心里轻松地扩展T const
。这就是在 boost 源中您在类型之后而不是之前看到 cv 限定符的原因。
The reason you face this error is because you write
const
before the type. Although this is common practise, it is not conducive to understanding how const/volatile-qualifiers (cv-qualifier) work.In this case
const T
whenT
ischar*
doesn't meanconst char*
. It rather meanschar* const
becauseT
ischar*
and no matter which side ofT
you putconst
it behaves as ifconst
is on the right ofT
, that is, the pointer itself that is going to be const not the type pointed too.It is easy to avoid this type of confusion if you make it a rule to always put
const
orvolatile
on the right of the type. For example, it makes it straightforward to mentally expandT const
whenT
ischar*
tochar* const
.This is the reason in boost sources you see cv-qualifiers after the type, not before.
将
const
移到&
之前Move
const
before&