C++模板对类的部分特化

usm*_*man 1 c++ templates template-specialization

我正在尝试使用类的C++部分模板专业化.问题更多的是语法而不是语义.其实我想要有以下内容:

int main()
{
   ...
   Reduce<int, float> r(new int, new float);
   Reduce<int> r2(new int); // partial template specialization?
   ...
}
Run Code Online (Sandbox Code Playgroud)

为了达到上述目的我试过:

template <typename T, typename U>
class Reduce {
  public:
    Reduce(T *t, U *u) { }
};

template <typename T>
class Reduce<T,T> {
  public:
    Reduce(T *t) { }
};
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,我不能使用以下语句:

Reduce<int> r2(new int); // error: wrong number of template arguments (1, should be 2)
Run Code Online (Sandbox Code Playgroud)

我还是要这样做:

Reduce<int, int> r2(new int); 
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下:(1)我怎样才能达到我想要的语法(如果可能的话)(2)如果不可能,为什么?(即技术问题)

hmj*_*mjd 5

为第二个模板类型指定默认类型:

template <typename T, typename U = int>
class Reduce {
  public:
    Reduce(T *t, U *u) { }
};
Run Code Online (Sandbox Code Playgroud)

或默认为与第一个模板类型相同:

template <typename T, typename U = T>
class Reduce {
  public:
    Reduce(T *t, U *u) { }
};
Run Code Online (Sandbox Code Playgroud)

例如,请参见http://ideone.com/5RcEG.