Reputation: 163
I want to pass any-type parameter to my function func1()
.
So here is my code:
myclass.h :
public:
myclass();
template<typename T> void func1(T object);
myclass.cpp :
template<typename T>
void myclass::func1(T object)
{
return;
}
main.cpp :
int a=0;
myclass::func1<int>(a);
But I got this error :
error: cannot call member function 'void myclass::func1(T) [with T = int]' without object
Where is my mistake?
Upvotes: 1
Views: 4163
Reputation: 606
You cannot simply separate declaration and definition in template functions. The simplest thing to do for a template function is to provide the code body in the function declaration in the header file.
If you want to call the function without a class object add static to the function signature.
header.hpp
#include <iostream>
class test_class{
public:
template<typename T> static void member_function(T t){
std::cout << "Argument: " << t << std::endl;
}
};
main.cpp
#include <iostream>
#include "header.hpp"
int main(int argc, char ** argv){
test_class::member_function(1);
test_class::member_function("hello");
}
Upvotes: 5