[英]Template class specialization for template class and other types
我的項目有問題,這是一些測試代碼,在項目中看起來相同。 一些類是普通的,但是其中之一是具有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
}
我知道我可以通過將B<int>
和B<double>
用作模板參數來做到這一點,但是它會使代碼加倍。 這是問題,我只想專門針對模板B類的方法,有什么辦法嗎? 我知道這段代碼行不通:
template< >
void
Test< B< _T> >::method()
{
////do sth for B< _T >
}
解決方案有點復雜,請參見內聯注釋以獲取一些解釋
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.