Class template + function call = error
Hi,
I am trying to become familiar with templates.
My goal : cout char if the object is initialized with a char, number otherwise.
Just a training.
Unfortunately, I might have missed something :)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
#include <iostream>
using namespace std;
template <class T>
class Bilou {
private :
T a;
public :
Bilou(T a){};
T tiger();
};
template <>
class Bilou <char> {
private :
char a;
public :
Bilou(char a){};
char tiger2();
};
char tiger2 () {
cout << "char";}
template <class T>
T Bilou<T>::tiger(){
cout << "number";}
int main(int argc, char *argv[])
{
Bilou <double>obj(54);
obj.tiger(); //here is the faulty line
return 0;
}
|
and the compiler shout after me :
required from here
where the line calls the function tiger (commented the code accordingly).
How can I manage it ?
Is it theoretically possible ?
Even with <double>obj.tiger(), it breaks.
Any suggestion ?
Thanks !
Larry
Last edited on
You have forgot to return a value from tiger().
Indeed Peter, that was that !
1 2 3 4
|
Bilou <double>obj(54);
double c = obj.tiger(); //here is the faulty line
if (c)
cout << "num";
|
Many thanks !
Cheers,
Larry
A better coding : with same class but specialized functions :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
#include <iostream>
#include <string>
using namespace std;
template <class T>
class Bilou {
private :
T a;
public :
Bilou(T a){};
int tiger();
};
template <>
int Bilou<char>::tiger() {
return 1;}
template <class T>
int Bilou<T>::tiger(){
return 2;}
int main(int argc, char *argv[])
{
Bilou <double>obj(54);
Bilou <int>obj2(54);
Bilou <char>obj3('q');
int c = obj2.tiger();
int q = obj3.tiger();
cout << c << endl << q << endl;
return 0;
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <iostream>
struct Bilou
{
static char Tiger( char ) { std::cout << "char: " ; return 'A' ; }
template < typename T >
static int Tiger( T ) { std::cout << "not char: " ; return 9 ; }
};
int main()
{
std::cout << Bilou::Tiger('A') << '\n' ; // char: A
std::cout << Bilou::Tiger(23) << '\n' ; // not char: 9
}
|
Exact !
My code above was intended to be a starting point for different functions implementations depending on the type.
But I am just a beginner :)
Topic archived. No new replies allowed.