13

Code:

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

};

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


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

ERROR:

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

Basically, I only want to specialize one function and use the common definition for other functions. (In actual code, I have many functions which I don't want to specialize).

How to do this? Thanks!

anon
  • 133
  • 1
  • 4

3 Answers3

10

Consider moving common parts to a base class:

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.

Alexandre C.
  • 55,948
  • 11
  • 128
  • 197
10

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
}
Tomek
  • 4,554
  • 1
  • 19
  • 19
  • 1
    This is how I would do it. A notable possibility is, if f2() should be specialized for each typename T, it could be also just declared inside the class (not implemented). This has the added benefit of compile-time check of implementation existence for given T (if it is not implemented, linker will complain.) – ondrejdee Jun 28 '13 at 07:16
2

When we declare specializations for a template class, we must also define all its members, even those exactly equal to the generic template class, because there is no inheritance of members from the generic template to the specialization. So, in your specialization you have to implement void f1(); too.

Mahesh
  • 34,573
  • 20
  • 89
  • 115
  • Thanks. Is there a workaround/syntax to avoid repeating code? (apart from `#define` of course). – anon Feb 10 '11 at 10:06