具有多个模板参数的模板类的单个方法的模板专门化 [英] Template specialization of a single method from templated class with multiple template parameters
问题描述
我基本上试图做模板类的模板专门化一个方法,除了我的TClass有多个模板参数,如下:
template<类KEY,类TYPE>
pre>
class TClass
{
public:
:
void doSomething(KEY * v);
:
};
template<类KEY,类TYPE>
void TClass< KEY,TYPE> :: doSomething(KEY * v)
{
// do something
}
这到目前为止,但是如何为一个模板参数定义一个专门的实现呢?我尝试添加:
模板< class TYPE>
void TClass< int,TYPE> :: doSomething(int * v)
{
//如果KEY是int则执行某些操作
}
,但编译器向该方法/函数提出无法匹配现有声明的函数定义(VC2010)。
如果我同时专门化两个模板参数,它的工作原理:
template< >
void TClass< int,char> :: doSomething(int * v)
{
//如果KEY是int,TYPE是char
, / code>但这不是我想做的。
?
解决方案在通过部分专门化定义方法之前,您必须专注于整个类:
template< typename T,typename U>
/ pre>
class TClass;
template< typename T>
class TClass< int,T>
{
void doSomething(int * v);
};
template< typename T>
void TClass< int,T> :: doSomething(int * v)
{
// ...
}
I'm basically trying to do what was discussed in Template specialization of a single method from a templated class except that my TClass has multiple template Parameters like this:
template < class KEY, class TYPE > class TClass { public: : void doSomething(KEY * v); : }; template < class KEY, class TYPE > void TClass<KEY, TYPE>::doSomething(KEY * v) { // do something }
This works so far, but how do I define a specialized implementation for one template Parameter? I tried adding this:
template < class TYPE > void TClass<int, TYPE>::doSomething(int * v) { // do something if KEY is int }
but the Compiler complains about "unable to match function Definition to an existing declaration" (VC2010) for that method/function.
As a sidenote: If I specialize both template Parameters at the same time, it works:
template < > void TClass<int, char>::doSomething(int * v) { // do something if KEY is int and TYPE is char }
but that's not what I want to do.
Any suggestions?
解决方案You have to specialize the entire class before you define a method through a partial specialization:
template <typename T, typename U> class TClass; template <typename T> class TClass<int, T> { void doSomething(int* v); }; template <typename T> void TClass<int, T>::doSomething(int* v) { // ... }
这篇关于具有多个模板参数的模板类的单个方法的模板专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!