在C++中,子类或朋友函数如何访问所有可能的父类模板类型?我如何修改下面的代码,以便无论类型T
是什么,朋友函数和子函数都不会遇到类型错误? (目前只有int的类型正常工作)。C++如何将模板应用于模板类的子/朋友?
// PARENT CLASS:¨
template <class T>
class parent{
public:
T variable1;
friend int function1(parent, int a);
};
//CHILD CLASS:
class child : public parent<int> {
public:
void setvariable(int a){ variable1 = a; };
};
// FRIEND FUNCTION:
int function1(parent<int> k, int a) {
return k.variable1 +a;
};
所以,下面再就没有错误编译:
int main() {
child child1; //Child
child child2;
child1.setvariable(4);
child2.setvariable(4.4); //Type error/retyping
cout << function1(child1.variable1, 4) << endl; // Function
cout << function1(child2.variable1, 4.0) << endl; // Type error
system("pause");
return 1;
}
的[声明模板类的模板友元函数]可能的复制(https://stackoverflow.com/questions/18792565/declare-template-friend-function-of-template-class) – AndyG
你能显示的代码示例你想拥有?例如,函数1的定义?对我而言,你不清楚你要求什么。 – Jonas
@Jonas函数的定义在第二行到最后一行;)。 – Tony