Reputation: 81
I want to declare a template member function in the class. As i know, we can declare that below case1. But it will make several classes, but i want to make only one class. I will not use the template to set member variable. I will use that only for parameter of member function. I want to make template function which can handle vary types in one class instance. So, is there any way to make template function in the one class?
//case1, standard template function
#include <iostream>
using namespace std;
template <typename T>
class A{
public:
void f(T n){
cout << n <<endl;
}
};
int main(){
A<int> a1;
a1.f(1);
A<float> a2;
a2.f(0.1);
}
//case2, i want to make member function which can receive vary type.
#include <iostream>
using namespace std;
class A{
public:
template <typename T>
void f(T n){
cout << n <<endl;
}
}
int main(){
A a();
a.f(1);
a.f(0.1);
}
Upvotes: 1
Views: 380
Reputation: 11028
Your code works for me after fixing a couple minor typos:
#include <iostream>
using namespace std;
class A{
public:
template <typename T>
void f(T n){
cout << n <<endl;
}
};
int main(){
A a;
a.f(1);
a.f(0.1);
}
$ g++ main.cc
./a.out
1
0.1
Upvotes: 2