C ++ - 模板专业化&部分专业化

时间:2012-11-18 21:10:54

标签: c++ templates class-template

我一直在寻找互联网和stackoverflow的具体答案,但我似乎无法找到一个。我必须创建一个泛型类,然后实现特定的功能。我的具体说明是:您需要使用模板表达式参数和模板类专业化和部分专业化。

我有一个模板类:

template <class T, int x, int y>
class Z {
    T **array[x][y];
    public:
         Z();
         void print();
         //and other methods
};

我需要:

1)只有Z = x = 2且y = 2需要公共方法void J()

2)对于x = 2且y = 2的char Z,J会做某事;对于其他一切它做其他事情

3)仅对于其中T为char的Z,将数组初始化为某个值。其他一切都是0

当然,这有效:

template<class T, int x, int y>
Z<T,x,y>::Z<T,x,y>() { //initialize to 0 } 

但这不是:

template<int x, int y>
Z<char,x,y>::Z<char,x,y>() { //initialize to something}

同样(假设J存在)这不起作用:

template <class T>
void Z<T,2,2>::J() { //something }

我的问题是:

有没有简单的方法来实现上述项目?我需要在Z中保留所有其他方法。给出一个提示或指向正确的方向(也许我错过了一个问题,因为有很多)会有所帮助。

感谢。

2 个答案:

答案 0 :(得分:5)

似乎您只想定义某些特化的某些函数:如果print()char特化和一般情况之间没有变化,那么您似乎不想重新定义它。

// What you want to do (illegal in C++)
template<int,typename T>
struct Z
{
    T myValue;
    Z();
    void print() { /* ... */ }
};

template<int i, typename T>
Z<i,T>::Z() { /* ... */ }

template<int i>
Z<i,char>::Z() { /* ... */ }

但是,它不会像这样工作。 除了模板参数的“原型”之外,类的部分或完全特化几乎没有任何共同之处:

// The two following types have only two things related: the template parameter is an int,
// and the second type is a full specialization of the first. There are no relations between
// the content of these 2 types.
template<int> struct A {};
template<> struct A<42> { void work(); };

您必须声明并定义每个(部分)专业化:

// Fixed example
template<int,typename T>
struct Z
{
    T myValue;
    Z();
    void print() { /* ... */ }
};
template<int i, typename T>
Z<i,T>::Z() { /* ... */ }

// Specialization for <all-ints,char>
template<int i>
struct Z<i,char>
{
    char myValue;
    char othervalue;
    Z();
    void print() { /* Same code than for the general case */ }
};

template<int i>
Z<i,char>::Z() { /* ... */ }

逃避代码重复的唯一方法是使用 traits 的继承:

// Example with the print function
template<typename T>
struct print_helper
{
    void print() { /* ... */ }
};

// Fixed example
template<int,typename T>
struct Z : public print_helper<T>
{
    T myValue;
    Z();
};
template<int i, typename T>
Z<i,T>::Z() { /* ... */ }

// Specialization for <all-ints,char>
template<int i>
struct Z<i,char> : public print_helper<char>
{
    char myValue;
    char othervalue;
    Z();
};

template<int i>
Z<i,char>::Z() { /* ... */ }

暂时无法执行您想要的操作(功能删除代码重复为static if,并且已针对下一个C ++标准提出,请参阅n3322和{{3} })。

答案 1 :(得分:0)

您可以查看此课程http://channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Core-C-/Stephan-T-Lavavej-Core-C-5-of-n

虽然您无法为函数模板定义部分特化,但您可以为类或结构模板定义部分特化。

template<typename T> struct helper {
    static void doThingy(){}
};

template<typename X> struct helper<X*> {
    static void doThingy(){}
};

Helper(double*)::doThingy();

在此示例中,仅当模板中的类型是指针类型时,才希望在doThingy()中专门化行为。在这种情况下,您不能使用方法doThingy()的重载。这是因为您不能重载没有参数的函数。但是你可以对struct helper进行部分特化。在专用模板中,您实现了doThingy()的希望行为。