使用模板将任意类型参数传递给 C++ 中的函数

passing any-type parameter to function in c++ using template

本文关键字:C++ 函数 参数传递 类型 任意      更新时间:2023-10-16

我想将任何类型的参数传递给我的函数func1()。 所以这是我的代码:myclass.h

public:
myclass();
template<typename T> void func1(T object);

我的班级.cpp

template<typename T> 
void myclass::func1(T object)
{
return;
}

主要.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");
}