Reputation: 251
I have a (simple) question about generic classes in c++. I have some knowledge of using them in C# like list but now I tried to implement one in c++ and i have a error and I don't know what i should do for the program to work. This is not a homework or something i need to but its research for myself.
Code:
#include <iostream>
using namespace std;
template<class A>class genericClass
{
A ceva;
char* clasa;
public:
void afisClasa(void);
genericClass(A);
~genericClass(void);
};
template<class A>genericClass<A>::afisClasa()
{
cout << clasa;
}
template<class A>genericClass<A>::genericClass(A myType)
{
myType = ceva;
if((int)ceva == ceva)
{
clasa = "INT";
goto label;
}
if((float)ceva == ceva)
{
clasa = "FLOAT";
goto label;
}
if((double)ceva == ceva)
{
clasa = "DOUBLE";
goto label;
}
label:
//cout << clasa;
}
template<class A>genericClass<A>::~genericClass(void)
{
}
int main()
{
int n;
genericClass<float> A(6.2);
cin >> n;
}
This program is supposed to take a generic number and to say what type it is, but when i implement the afisClass method i get an error:
C4430: Missing type specifier - int assumed. Note c++ does not support default-in
Upvotes: 1
Views: 6469
Reputation: 754893
This is a case where you'd likely want to do template specialization. C++ allows you to customize the behavior of a template based off it's instantiated type. For example
template <typename T>
void PrintMyType(T& arg) {
cout << "Unknown type" << endl;
}
template <>
void PrintMyType<int>(int& arg) {
cout << "int" << endl;
}
template <>
void PrintMyType<float>(float& arg) {
cout << "float" << endl;
}
PrintMyType(42); // prints "int"
PrintMyType("hello"); // prints "Unknown type"
Upvotes: 0
Reputation: 477150
You have to say:
template <class A> void genericClass<A>::afisClasa() { cout << clasa; }
// ^^^^
The function definition has to have the exact same form as the previous declaration.
Upvotes: 6