JBe*_*Fat 0 c++ templates overloading partial-specialization
在堆栈溢出上已经有一些类似于此的问题,但似乎没有什么能直接回答我的问题.如果我重新发布,我会道歉.
我想重载一些模板化类的方法(带有2个模板参数),并对这些方法进行部分模板特化.我无法弄清楚正确的语法,并开始认为这是不可能的.我以为我会在这里发帖,看看能不能得到确认.
要遵循的示例代码:
template <typename T, typename U>
class Test
{
public:
void Set( T t, U u );
T m_T;
U m_U;
};
// Fully templated method that should be used most of the time
template <typename T, typename U>
inline void Test<T,U>::Set( T t, U u )
{
m_T=t;
m_U=u;
}
// Partial specialisation that should only be used when U is a float.
// This generates compile errors
template <typename T>
inline void Test<T,float>::Set( T t, float u )
{
m_T=t;
m_U=u+0.5f;
}
int _tmain(int argc, _TCHAR* argv[])
{
Test<int, int> testOne;
int a = 1;
testOne.Set( a, a );
Test<int, float> testTwo;
float f = 1.f;
testTwo.Set( a, f );
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以写出整个班级的部分专业,但这有点糟透了.这样的事情可能吗?
(我正在使用VS2008)编辑:这是编译错误错误C2244:'Test :: Set':无法将函数定义与现有声明匹配
谢谢 :)
如果不定义类模板本身的部分特化,则不能部分地专门化成员函数.请注意,模板的部分特化是STILL模板,因此当编译器看到时Test<T, float>,它期望类模板的部分特化.
-
C++标准(2003)的14.5.4.3/1美元说,
类模板部分特化的成员的模板参数列表应匹配类模板部分特化的模板参数列表.类模板部分特化的成员的模板参数列表应匹配类模板部分特化的模板参数列表.类模板特化是一个独特的模板.类模板部分特化的成员与主模板的成员无关.应定义以需要定义的方式使用的类模板部分特化成员; 主模板成员的定义从不用作类模板部分特化的成员的定义.类模板部分特化的成员的显式特化以与主模板的显式特化相同的方式声明.
然后标准本身给出了这个例子,
// primary template
template<class T, int I> struct A {
void f();
};
template<class T, int I> void A<T,I>::f() { }
// class template partial specialization
template<class T> struct A<T,2> {
void f();
void g();
void h();
};
// member of class template partial specialization
template<class T> void A<T,2>::g() { }
Run Code Online (Sandbox Code Playgroud)
我希望标准中的引用和示例能够很好地回答您的问题.