Make a class template to hold objects

Hi. I want to make a class template and then make a simple object which will be stored in the template class..this is my code

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
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <string>
#include <typeinfo>

using namespace std;

template <class T>
class Generic {

    private:

        T object;
        int items;

    public:
         Generic(T instance, int no_items);
        ~Generic();
       
};

template <class T>
Generic<T>::Generic(T instance, int no_items){

    object=instance;
    items=no_items;

        cout<<typeid(object); //cannot print out says << no match...how can I         solve this

}


template <class T>
Generic<T>::~Generic(){}

class Test{

    private:

        int num;

};

int main(){

    Test test;
    int items;
    cout<<"Enter X items: ";
    cin>>items;
    Generic<Test> gen(test, items);
    
}
If you want to print out the object you should not use typeid

 
cout << object;

For this to work there must be a matching overload of operator<<.

1
2
3
4
5
std::ostream& operator<<(std::ostream& os, const Test& t)
{
	os << "Test..."; // Output t here the way you want it.
	return os;
}
Last edited on
But if you are for some or other reason actually trying to print out the type name for the object, then you need line 27 to read:

cout<<typeid(object).name();

Note that the name returned when code is built with GCC is 'mangled' so needs to be 'unmangled' if you want a human readable version. As done here:
http://www.cplusplus.com/forum/beginner/166020/#msg836699

Andy
Last edited on
thanks, it seems to work now. :)
Topic archived. No new replies allowed.