相关疑难解决方法(0)

组类模板特化

是否有一种技术/最佳风格可以为某些类型分组类模板特化?

一个例子:假设我有一个类模板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)

c++ templates traits enable-if c++11

11
推荐指数
2
解决办法
1257
查看次数

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

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

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)

c++ templates type-traits template-specialization

5
推荐指数
1
解决办法
1017
查看次数