ZAB
ZAB

Reputation: 1015

Specialize template member inside template definition

It is possible to specialize some class member function outside the template definition:

template<class A>
struct B {
   void f();   
};

template<>
void B<int>::f() { ... }

template<>
void B<bool>::f() { ... }

and in this case I can even omit definition of function f for a general type A.

But how to put this specializations inside the class? Like this:

template<class A>
struct B {
   void f();   

   void f<int>() { ... }
   void f<bool>() { ... }
};

What syntax should I use in this case?

EDIT: For now the solution with fewest lines of code is to add a fake template function f definition and explicitly call it from original function f:

template<class A>
struct B {
   void f() { f<A>(); }

   template<class B> 
   void f();

   template<> 
   void f<int>() { ... }

   template<> 
   void f<bool>() { ... }
};

Upvotes: 2

Views: 179

Answers (3)

bjhend
bjhend

Reputation: 1713

You can make B::f a template function within your struct:

struct B {
    template <typename T>
    void f();

    template<>
    void f<int>() { ... }

    template<>
    void f<bool>() { ... }
};

Edit:

According to your comment this may help you, but I've not tested if it works:

template <typename A>
struct B {
    template <typename T = A>
    void f() { ... }

    template<>
    void f<int>() { ... }

    template<>
    void f<bool>() { ... }
};

Upvotes: 4

alfa
alfa

Reputation: 3088

#include<iostream>
using namespace std;

template<class A>
class B
{
public:
  void f() {
    cout << "any" << endl;
  }
};

template<>
class B<int>
{
public:
  void f() {
    cout << "int" << endl;
  }
};

int main()
{

  B<double> b1;
  b1.f();
  B<int> b2;
  b2.f();
  return 0;
}

Output:

any
int

Anything else is not possible.

Upvotes: 0

orlp
orlp

Reputation: 117771

You should put the specialization on the struct:

template<>
struct B<int> {
   void f() { ... }
};

template<>
struct B<bool> {
   void f() { ... }
};

There is no way to specialize member functions in the same class the templated version is defined in. Either you must explicitly specialize the member function outside of the class, or specialize an entire class with the member function in it.

Upvotes: 6

Related Questions