我想将任何类型的参数传递给我的函数 func1()
。
所以这是我的代码:
我的类.h :
public:
myclass();
template<typename T> void func1(T object);
我的类.cpp:
template<typename T>
void myclass::func1(T object)
{
return;
}
main.cpp :
int a=0;
myclass::func1<int>(a);
但是我得到了这个错误:
error: cannot call member function 'void myclass::func1(T) [with T = int]' without object
我的错误在哪里?
最佳答案
您不能简单地将模板函数中的声明和定义分开。对于模板函数,最简单的做法是在头文件中的函数声明中提供代码体。
如果您想在没有类对象的情况下调用函数,请将静态添加到函数签名中。
标题.hpp
#include <iostream>
class test_class{
public:
template<typename T> static void member_function(T t){
std::cout << "Argument: " << t << std::endl;
}
};
主要.cpp
#include <iostream>
#include "header.hpp"
int main(int argc, char ** argv){
test_class::member_function(1);
test_class::member_function("hello");
}
关于c++ - 使用模板将任何类型的参数传递给 c++ 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45281602/