5

is it possible to write a partial template specialization that is used only for class types that, for example, inherit from a specific class or comply with some other constraint that can be expressed via type traits? i.e., something like this:

class A{}

class B : public A{}

template<typename T>
class X{
    int foo(){ return 4; }
};

//Insert some magic that allows this partial specialization
//only for classes which are a subtype of A
template<typename T> 
class X<T>{
    int foo(){ return 5; }
};

int main(){
    X<int> x;
    x.foo(); //Returns 4
    X<A> y;
    y.foo(); //Returns 5
    X<B> z;
    z.foo(); //Returns 5
    X<A*> x2; 
    x2.foo(); //Returns 4
}
gexicide
  • 38,535
  • 21
  • 92
  • 152
  • Duplicate of http://stackoverflow.com/questions/1032973/how-to-partially-specialize-a-class-template-for-all-derived-types ? – Jon Hanna Aug 28 '12 at 14:10

1 Answers1

13

Usually if you want conditional partial template specialization, you'll need to provide an extra parameter, and then use enable_if:

template<typename T, typename=void>
class X {
public:
    int foo(){ return 4; }
};

template<typename T>
class X<T, std::enable_if_t<std::is_base_of_v<A, T>>> {
public:
    int foo(){ return 5; }
};
Indiana Kernick
  • 5,041
  • 2
  • 20
  • 50
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005