c ++函数模板专业化 [英] c++ function template specialisation
问题描述
代码如下:
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
{
}
$ b b
当我编译它,我得到以下错误。
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
推荐答案
你面对这个错误的原因是因为你写了 const
之前的类型。虽然这是常见的做法,但它不利于了解const / volatile-qualifiers(cv-qualifier)是如何工作的。
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.
在这种情况下 const当
T
是 char *
不表示 const char *
。因为 T
是 char *
,所以代表 char * const
并且不管 T
的哪一侧,你放置 const
,其行为如同 const
在 T
的右边,也就是说,指针本身将是const不是指向的类型。
In this case const T
when T
is char*
doesn't mean const char*
. It rather means char* const
because T
is char*
and no matter which side of T
you put const
it behaves as if const
is on the right of T
, that is, the pointer itself that is going to be const not the type pointed too.
如果你把一个规则总是 const
或 volatile
在类型的右边。例如,当 T
是 char * <>时,它可以直观地扩展
T const
/ code>到 char * const
。
It is easy to avoid this type of confusion if you make it a rule to always put const
or volatile
on the right of the type. For example, it makes it straightforward to mentally expand T const
when T
is char*
to char* const
.
在类型之后,而不是之前。
This is the reason in boost sources you see cv-qualifiers after the type, not before.
这篇关于c ++函数模板专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!