是否有一种技术/最佳风格可以为某些类型分组类模板特化?
一个例子:假设我有一个类模板Foo,我需要为排版设置相同的专用模板
A = { Line, Ray }
Run Code Online (Sandbox Code Playgroud)
而另一种方式是排版B.
B = { Linestring, Curve }
Run Code Online (Sandbox Code Playgroud)
#include <iostream>
#include <type_traits>
using namespace std;
// 1st group
struct Line {};
struct Ray {};
// 2nd group
struct Curve {};
struct Linestring {};
template<typename T, typename Groupper=void>
struct Foo
{ enum { val = 0 }; };
// specialization for the 1st group
template<typename T>
struct Foo<T, typename enable_if<
is_same<T, Line>::value ||
is_same<T, Ray>::value
>::type>
{ …Run Code Online (Sandbox Code Playgroud) 是否可以编写仅用于类类型的部分模板特化,例如,从特定类继承或遵守可通过类型特征表达的其他约束?即,像这样:
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)