c++ - 将带有模板类参数的构造函数传递给另一个函数

标签 c++

我有一个类,其构造函数必须使用模板类参数进行初始化。现在,我需要将此类的构造函数传递给 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/

相关文章:

c++ - reshape 微软的 Concurrency::diagnostic::span 也可以检测外部跨度

c++ - 执行 native NodeJS 模块时,Electron 卡住

c++ - 丢弃理论上使用但技术上未使用的功能

c++ - 在 Qt 中使用 $HOME

C++ std::accumulate 没有给出预期的总和

c++ - 传递变量值以使用 cmake

c++ - 在 _USE_32BIT_TIME_T 上使用 C++11 的计时

c++ - 修改 Duff 设备的语法 - 这是合法的 C/C++ 吗?

c++ - 解析和编译命名法

c++ - 使用 C++11 的成员初始化列表中的初始化列表语法