我有一个类,其构造函数必须使用模板类参数进行初始化。现在,我需要将此类的构造函数传递给 main()
中的另一个方法。但我正在尝试这样做,它会引发错误,而且我无法获得解决方案。
template<class K>
Class Student
{
friend void printFunction();
public:
Student(K val)
{std::cout<<val;}
};
void printFunction(Student object)
{
......
}
int main()
{
Student <int> object(10);
printFunction(object); //This line throws an error
}
这是错误信息:
error: use of class template 'Student' requires template arguments
最佳答案
您的代码有几个问题。第一个也是简单的方法是将类名 Student
传递给 printFunction
的调用。您应该改为调用 printFunction(object)
。
其次,要使 printFunction
接受模板类 Student
的实例,您还需要将其设为模板。请参阅下面的工作示例。
#include <iostream>
template<class K>
class Student;
template<class K>
void printFunction(Student<K> object)
{
std::cout << object.val;
}
template<class K>
class Student
{
friend void printFunction<>(Student<K>);
public:
Student(K val) : val(val) {}
private:
K val;
};
int main()
{
Student<int> object(10);
printFunction(object);
}
关于c++ - 将带有模板类参数的构造函数传递给另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32787198/