部分模板专业化仅限于某些类型 [英] Partial Template Specialization restricted to certain types
本文介绍了部分模板专业化仅限于某些类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以编写一个只用于类类型的部分模板特化,例如从一个特定的类继承或遵守一些可以通过类型特征表达的其他约束?
ie,像这样:
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
}
推荐答案
您需要提供一个额外的参数,然后使用enable_if:
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, typename std::enable_if<std::is_base_of<A, T>::value>::type> {
public:
int foo(){ return 5; }
};
这篇关于部分模板专业化仅限于某些类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文