12

代码:

template<class T>
struct A {
  void f1() {};
  void f2() {};

};

template<>
struct A<int> {
  void f2() {};
};


int main() {
  A<int> data;
  data.f1();
  data.f2();
};

错误:

test.cpp: In function 'int main()':
test.cpp:16: error: 'struct A<int>' has no member named 'f1'

基本上,我只想专门化一个函数,而对其他函数使用通用定义。(在实际代码中,我有很多我不想专门研究的功能)。

这该怎么做?谢谢!

4

3 回答 3

10

考虑将公共部分移动到基类:

template <typename T>
struct ABase
{
    void f1();
};


template <typename T>
struct A : ABase<T>
{
    void f2();
}  


template <>
struct A<int> : ABase<int>
{
    void f2();
};

You can even override f1 in the derived class. If you want to do something more fancy (including being able to call f2 from f1 code in the base class), look at the CRTP.

于 2011-02-10T10:06:09.270 回答
9

Would this help:

template<typename T>
struct A
{
  void f1()
  {
    // generic implementation of f1
  }
  void f2()
  {
    // generic implementation of f2
  }
};

template<>
void A<int>::f2()                                                               
{
  // specific  implementation of f2
}
于 2011-02-10T20:07:36.577 回答
2

当我们为模板类声明特化时,我们还必须定义它的所有成员,即使是那些与泛型模板类完全相同的成员,因为从泛型模板到特化没有成员继承。因此,在您的专业中,您也必须实施void f1();

于 2011-02-10T10:04:10.770 回答