Partial Template Specialization restricted to certain types

百般思念 提交于 2020-01-02 04:05:27

问题


is it possible to write a partial template specialization that is used only for class types that, for example, inherit from a specific class or comply with some other constraint that can be expressed via type traits? i.e., something like this:

class A{}

class B : public A{}

template<typename T>
class X{
    int foo(){ return 4; }
};

//Insert some magic that allows this partial specialization
//only for classes which are a subtype of A
template<typename T> 
class X<T>{
    int foo(){ return 5; }
};

int main(){
    X<int> x;
    x.foo(); //Returns 4
    X<A> y;
    y.foo(); //Returns 5
    X<B> z;
    z.foo(); //Returns 5
    X<A*> x2; 
    x2.foo(); //Returns 4
}

回答1:


Usually if you want conditional partial template specialization, you'll need to provide an extra parameter, and then use enable_if:

template<typename T, typename=void>
class X {
public:
    int foo(){ return 4; }
};

template<typename T>
class X<T, std::enable_if_t<std::is_base_of_v<A, T>>> {
public:
    int foo(){ return 5; }
};


来源:https://stackoverflow.com/questions/12161033/partial-template-specialization-restricted-to-certain-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!