Search code examples
c++templatessfinaeenable-if

"Faking" Template class method specialization with enable_if


I wonder if the SFINAE principle/enable_if's can be used to "fake" the partial specialization of the class template method. For example, given the class template Foo in which two versions of Foo::bar are defined. I'd like to enable one and disable the other if T2 = int (for example) and vice-versa.

template<typename T1, typename T2>
struct Foo
{
    void bar();
};

// Enable if T2 != int (disable otherwise)
template<typename T1, typename T2>
void Foo<T1,T2>::bar()
{
}

// Enable if T2 == int (disable otherwise)
template<typename T1, typename T2>
void Foo<T1,T2>::bar()
{
}

PS: boost enable_if's preferred please. Thanks.


Solution

  • [Edited.] You can produce different overloads by typifying boolean values:

    #include <type_traits>
    
    template <typename T1, typename T2>
    struct Foo
    {
        void bar_impl(std::true_type);
        void bar_impl(std::false_type);
    
        void bar() { bar_impl(std::is_same<T2, int>()); }
    };