Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specialize template member inside template definition

Tags:

c++

templates

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>() { ... }
};
like image 559
ZAB Avatar asked Jun 27 '26 00:06

ZAB


1 Answers

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.

like image 80
orlp Avatar answered Jun 29 '26 13:06

orlp