简体   繁体   中英

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.

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 */ }
};

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