Search code examples
c++c++11sfinaeenable-if

How to constrain class templates and data members with std::enable_if


I have a class template:

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

I only want to instantiate it when a + b == 10. Could I make this possible using std::enable_if?

Furthermore, if I have a data member in class foo:

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

I only want to have 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

  • I guess you can use static_assert better to enforce that constraint instead of enable_if

    template<int a, int b>
    class foo {
        static_assert(a+b==10, "a+b is not 10");
    };
    
    int main()
    {
        foo<5,5> f; // will compile
        foo<1,5> f; // will fail to compile with error: a+b is not 10
        return 0;
    }
    

    enable_if is primarily used to conditionally remove functions and classes from overload resolution based on type traits and to provide separate function overloads and specializations for different type traits.