部分模板专业化仅限于某些类型

gex*_*ide 5 c++ templates type-traits template-specialization

是否可以编写仅用于类类型的部分模板特化,例如,从特定类继承或遵守可通过类型特征表达的其他约束?即,像这样:

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
}
Run Code Online (Sandbox Code Playgroud)

ken*_*ytm 10

通常,如果您需要条件局部模板特化,则需要提供额外参数,然后使用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; }
};
Run Code Online (Sandbox Code Playgroud)