Edward Diener
Edward Diener

Reputation: 147

Specializing class template member function based on type requirement in C++11

Given a class template of:

template<typename T>
class AAA
    {
    void XXX(T val) { /* code */ }
    void YYY(T val) { /* code */ }
    };

I know I can specialize the member function XXX for a particular type such as an 'int' with:

template<> void AAA<int>::XXX(int val) { /* code * }

but what I really want to do is specialize the XXX function based not on a particular type for T but based on a particular type requirement for T, such as that T should be copy_constructible, as an example. I am aware of how std::enable_if works but can not come up with the correct C++ syantax to do what I want. Please note that I know a technique that would enable me to partially specialize the class template itself for T being copy-constructible, but I do not want to do that.

Upvotes: 2

Views: 249

Answers (1)

yeputons
yeputons

Reputation: 9238

You cannot partially specialize a function, but you can partially specialize a whole class:

template<typename T, typename /* placeholder so there is a place for SFINAE */ = void>
class AAA
{
    void XXX(T val) { /* code */ }
    void YYY(T val) { /* code */ }
};

template<typename T>
class AAA<T, std::enable_if_t<std::is_copy_constructible_v<T>>>
{
    void XXX(T val) { /* code when T is copy constructible */ }
    void YYY(T val) { /* code when T is copy constructible */ }
};

Upvotes: 2

Related Questions