简体   繁体   中英

“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.

[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>()); }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM