c++ - 模板类专门针对模板类和其他类型

标签 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
}

我知道我可以通过专门化来做到这一点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>
}

关于c++ - 模板类专门针对模板类和其他类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18844262/

相关文章:

c++ - 我该如何定义这个复杂的函数模板呢?

c++ - C++ 中的动态(类型)二进制缓冲区?

c++ - 在 C++ 中使用迭代器围绕 STL 类编写包装器

c++ - C++ 模板类中的等效实例

javascript - 编译后操作模板

c++ - 为什么在这种情况下模板参数是引用?

c++ - 一个 TU 中的模板特化被另一个 TU 隐藏

c++ - 将 freetype 与 cmake 链接起来

c++ - 垂直布局 QTableView 的范例方式

c++ - 从 C++ 应用程序在 Excel 中绘制图形