1

我正在尝试使用类进行 C++ 部分模板专业化。这个问题更多的是关于语法而不是语义。其实我想要有如下的东西:

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

为了实现上述目标,我尝试了:

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

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

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

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

我仍然必须这样做:

Reduce<int, int> r2(new int); 

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

4

3 回答 3

5

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

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

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

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

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

于 2012-07-02T10:52:25.630 回答
4

根据您最终想要的,这可能是也可能不是解决方案,但至少它可以编译:

template <typename... T>
class Reduce;

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

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

int main()
{
   Reduce<int, float> r(new int, new float);
   Reduce<int> r2(new int); // partial template specialization?
}
于 2012-07-02T10:54:14.063 回答
0

从您的模板声明

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

您可以看到您需要为 Reduce 提供 2 个模板参数。所以也要改变你的用法

Reduce<int,int> r2(new int)
于 2012-07-02T10:50:10.977 回答