Search code examples
c++stdenable-if

std::enable_if second ask


I am quite new to std::enable_if and wondering how to use it. I have a template class:

template<int a, int b>
class foo {
  int c;
}

I only want the template to have member c when

a = 5. 

How do I do that using std::enable_if? Is this one the correct case to use std::enable_if?


Solution

  • You can use partial specialization. No need of std::enable_if.

    //primary template
    template<int a, int b>
    class foo 
    {
          //whatever 
    };
    
    //partial specialization
    template<int b>
    class foo<5,b>  //when a = 5, this specialization will be used!
    {
      int c;  //it has member c
    };
    

    Usage:

    foo<1,3>  f1; //primary template is used
    foo<5,3>  f2; //partial specialization is used