[英]Template class specialization for template class and other types
I have problem with my project, here is some test code, in project it looks same. 我的项目有问题,这是一些测试代码,在项目中看起来相同。 Some of classes are plain but one of them is template class with 2 different types (class B) for example int and double.
一些类是普通的,但是其中之一是具有2种不同类型(B类)的模板类,例如int和double。
class Bar
{
Bar()
{
}
};
template< typename _T >
class B
{
B();
};
template< typename _T >
B<_T>::B()
{
}
typedef B<int> Bint;
typedef B<double> Bdouble;
template< typename _T >
class Test
{
Test();
void method();
};
template< typename _T >
Test<_T>::Test()
{
}
template< typename _T >
void
Test<_T>::method()
{
}
template< >
void
Test< Bar >::method()
{
//do sth for Bar
}
I know i can do it by spcializing B<int>
and B<double>
for template argument but it doubles the code. 我知道我可以通过将
B<int>
和B<double>
用作模板参数来做到这一点,但是它会使代码加倍。 Here is te problem, i want to specialize method for only template B class, is ther any way to do it ? 这是问题,我只想专门针对模板B类的方法,有什么办法吗? I know this code won't work :
我知道这段代码行不通:
template< >
void
Test< B< _T> >::method()
{
////do sth for B< _T >
}
The solution is a bit complicated, see the inline comments for some explanation 解决方案有点复杂,请参见内联注释以获取一些解释
class Bar
{
Bar() {}
};
template< typename T >
class B
{
B() {}
};
typedef B<int> Bint;
typedef B<double> Bdouble;
template< typename T >
class Test
{
Test() {}
private:
// you need one level of indirection
template<typename U> struct method_impl
{
static void apply();
};
// declare a partial specialization
template<typename X> struct method_impl< B<X> >
{
static void apply();
};
public:
// forward call to the above
void method() { method_impl<T>::apply(); }
};
// and now you can implement the methods
template< typename T >
template< typename U >
void
Test<T>::method_impl<U>::apply()
{
// generic implementation
}
template<>
template<>
void
Test< Bar >::method_impl<Bar>::apply()
{
//do sth for Bar
}
template< typename T >
template< typename X >
void
Test< T >::method_impl< B<X> >::apply()
{
//do sth for B<X>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.