整个参数集的模板专门化

template specialisation for a whole set of parameters

本文关键字:专门化 参数      更新时间:2023-10-16

可能很容易解决,但很难找到解决方案:

是否有可能(部分地)专门化一整组类型?在这个例子中,"Foo"应该部分特化为(T,int)和(T,double),只有一个模板定义。

我能做的是为(T,int)定义一个专门化。见下文。但是,对于(T,int) (T,double),它应该只有一个函数定义(没有代码double)。

template <typename T,typename T2>
struct Foo
{
  static inline void apply(T a, T2 b) 
  {
    cout << "we are in the generic template definition" << endl;
  }
};
// partial (T,*)
template <typename T>
struct Foo<T, int >     // here something needed like T2=(int, double)
{
  static inline void apply(T a, T2 b) 
  {
    cout << "we are in the partial specialisation for (T,int)" << endl;
  }
};

对于(T,int)和(T,double)有什么想法吗?

如果我正确理解了你的问题,那么你可以编写一个基类模板并从中派生,如下所示:

template <typename T, typename U>
struct Foo_Base
{
  static inline void apply(T a) 
  {
    cout << "we are in the partial specialisation Foo_Base(T)" << endl;
  }
};
template <typename T>
struct Foo<T, int> : Foo_Base<T, int> {};
template <typename T>
struct Foo<T, double> : Foo_Base<T, double> {};

虽然它不是一个模板定义(如你所要求的),但你可以避免代码重复。

Demo: http://www.ideone.com/s4anA

我相信您可以使用Boost的enable_if来为您想要的类型启用部分专门化。第3.1节展示了如何做,并给出了这个例子:

template <class T, class Enable = void> 
class A { ... };
template <class T>
class A<T, typename enable_if<is_integral<T> >::type> { ... };