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

aoi*_*aoi 4 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
};
Run Code Online (Sandbox Code Playgroud)

我需要:

1)只有Z的,其中x = 2和y = 2需要有一个公共方法void J()

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

3)对于只有Z是char的字符,将数组初始化为某个值.其他一切都是0

当然,这有效:

template<class T, int x, int y>
Z<T,x,y>::Z<T,x,y>() { //initialize to 0 } 
Run Code Online (Sandbox Code Playgroud)

但这不是:

template<int x, int y>
Z<char,x,y>::Z<char,x,y>() { //initialize to something}
Run Code Online (Sandbox Code Playgroud)

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

template <class T>
void Z<T,2,2>::J() { //something }
Run Code Online (Sandbox Code Playgroud)

我的问题是:

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

谢谢.

Syn*_*xis 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() { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

逃避代码重复的唯一方法是使用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() { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

目前你无法做到你想做的事情而没有重复(删除代码重复的功能static if已被提出用于下一个C++标准,请参阅n3322n3329).