模板类和其他类型的模板类专门化

时间:2013-09-17 07:54:08

标签: c++ templates template-specialization

我的项目有问题,这里有一些测试代码,在项目中它看起来一样。一些类是普通的,但其中一个是具有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
}

我知道我可以通过对模板参数进行spcializing B<int>B<double>来实现它,但它会使代码加倍。这是te问题,我想专门针对模板B类的方法,还有什么办法呢? 我知道这段代码不起作用:

template< >
void
Test< B< _T> >::method()
{
   ////do sth for B< _T >
}

1 个答案:

答案 0 :(得分:3)

解决方案有点复杂,请参阅内联注释以获得一些解释

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>
}
相关问题