【发布时间】:2012-11-06 19:59:04
【问题描述】:
我一直在互联网和 stackoverflow 上寻找具体答案,但我似乎找不到。我必须创建一个通用类,然后实现特定的功能。我的具体说明是:您需要使用模板表达式参数和模板类专业化和部分专业化。
我有一个模板类:
template <class T, int x, int y>
class Z {
T **array[x][y];
public:
Z();
void print();
//and other methods
};
我需要:
1) 只有 x= 2 和 y = 2 的 Z 需要公共方法 void J()
2) 对于 x = 2 和 y= 2 的字符 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 中。给出提示或指出正确的方向(可能我错过了一个问题,因为有很多问题)会有所帮助。
谢谢。
【问题讨论】:
-
你有哪些错误?
J是什么?不清楚你想做什么。 -
J 是一些函数。我需要做的是列出1,2,3。我的错误是(下一个 cmets):
-
For Z
::Z () { //stuff } : “'之前 -
并假设 J 存在:void Z
::J() {//stuff} 给出错误:“无效使用未定义类型 class Z<char, x, y>'" and "template definition of non-templatevoid Z::J()' "
标签: c++ templates class-template