array of templated struct

Started by
5 comments, last by bkt 19 years, 2 months ago
I want to create a struct that looks like this: template <typename T> struct A { int foo; T other; }; I want to create a list or array of this struct for any type of T. Like this: { A<int>, A<bool>, A<OtherClass>, A<float>, A<int>, ... } All I know is you can create an array but the elements must share the same T. I don't know if you can vary the T in the same array. Can somebody give me some pointers? edit: I know you can't vary T because all elements must be the same size in an array. But I need an alternative that achieves the same effect.
Advertisement
There's a couple of ways to achive the desired effect. Which one is best depends on what you're doing. We could use inheritence, ala:

struct Base{    int foo;};template < typename T > struct Derived : public Base{    T bar;};std::vector< Base * > objects;objects.push_back( new Derived<int> );objects.push_back( new Derived<char> );objects[0].foo = 4;objects[1].foo = 3;


If you want to access bar, however, things get more tricky. Virtual functions will come into play, most likely. But that depends on exactly what you're doing :). It may be as simple as implementing a virtual function in Base/Derived<...>. If that dosn't model your situation very well, you'll probably want to check out established practices, such as the Visitor Pattern, and although The traditional variation might not work well in C++ using template parameters, some of the variations in this wiki might model your situation nicely (such as the Independent Visitor Pattern)

[Edited by - MaulingMonkey on February 12, 2005 9:50:14 PM]
The problem isn't just to do with size of the type, but the fact that the types A<int> and A<bool> are two totally different types as far as the compiler is concerned, and you can't make an array that can contain different types (at least, not directly).

Just what is it that you need this for? IMHO, you should rethink just why you need an array of different types. Perhaps you can create an interface for your desired functionallity that the templated struct derives from and store an array of pointers to that interface?
"Voilà! In view, a humble vaudevillian veteran, cast vicariously as both victim and villain by the vicissitudes of Fate. This visage, no mere veneer of vanity, is a vestige of the vox populi, now vacant, vanished. However, this valorous visitation of a bygone vexation stands vivified, and has vowed to vanquish these venal and virulent vermin vanguarding vice and vouchsafing the violently vicious and voracious violation of volition. The only verdict is vengeance; a vendetta held as a votive, not in vain, for the value and veracity of such shall one day vindicate the vigilant and the virtuous. Verily, this vichyssoise of verbiage veers most verbose, so let me simply add that it's my very good honor to meet you and you may call me V.".....V
I have thought of using inheritance but for some reason I dumped out that idea. I don't remember why.

Quote:Original post by joanusdmentia
Just what is it that you need this for? IMHO, you should rethink just why you need an array of different types. Perhaps you can create an interface for your desired functionallity that the templated struct derives from and store an array of pointers to that interface?

I am trying to create a list of events, which later can be polled. Each event will have it's own information depending on what kind of event it is. A mouse move event will have the coordinate, a keyboard event will have the key pressed, a bomb exploded nearby may have the location, and other events may have other information attached to it. That's why I need the template so that user can define his own event. I think I could use inheritance, let me rethink this for awhile.
Something like this should work; not near a compiler right now so I can't test it out. You can make a base class for templates and then make that a child class of a vector (array) of the Type. Some pseudo below:
template<class T>class CTemplateArray : public std::vector<T*> {  public:    ...};

Works rather well; thank the C++ Gods for inheritance; comes into very good use when you want to do specific sorting for each type of array that you have. I'm currently using a similar method for sorting my file table information for custom archive format.

Here's a working example:
typedef CFile*			ffile_t;class CFileArray : public array_t<ffile_t> {	public:		~CFileArray(void) {			for(iterator p=begin(); p != end(); p++)				delete *p;		}		inline void Sort(void) {			std::sort(begin(),end(), Sort_By_Position() );		}	private:		struct Sort_By_Position {			bool operator() (ffile_t& start,ffile_t& end) {				return (start->GetPosition() < end->GetPosition());			}		};};
-John "bKT" Bellone [homepage] [[email=j.bellone@flipsidesoftware.com]email[/email]]
Quote:Original post by alnite
I am trying to create a list of events, which later can be polled. Each event will have it's own information depending on what kind of event it is. A mouse move event will have the coordinate, a keyboard event will have the key pressed, a bomb exploded nearby may have the location, and other events may have other information attached to it. That's why I need the template so that user can define his own event. I think I could use inheritance, let me rethink this for awhile.


Hmm, I'd be surprised if you really need templates then. Off the top of my head.....

class Event{public:    virtual void triggerEvent() =0;};class MouseEvent : public Event{    int x, y;    int buttonmask;public:    MouseEvent(int x, int y, int buttonmask)        : x(x), y(y), buttonmask(buttonmask) {}    virtual void triggerEvent()    {        // do stuff    }};
"Voilà! In view, a humble vaudevillian veteran, cast vicariously as both victim and villain by the vicissitudes of Fate. This visage, no mere veneer of vanity, is a vestige of the vox populi, now vacant, vanished. However, this valorous visitation of a bygone vexation stands vivified, and has vowed to vanquish these venal and virulent vermin vanguarding vice and vouchsafing the violently vicious and voracious violation of volition. The only verdict is vengeance; a vendetta held as a votive, not in vain, for the value and veracity of such shall one day vindicate the vigilant and the virtuous. Verily, this vichyssoise of verbiage veers most verbose, so let me simply add that it's my very good honor to meet you and you may call me V.".....V
Quote:Original post by joanusdmentia
Quote:Original post by alnite
I am trying to create a list of events, which later can be polled. Each event will have it's own information depending on what kind of event it is. A mouse move event will have the coordinate, a keyboard event will have the key pressed, a bomb exploded nearby may have the location, and other events may have other information attached to it. That's why I need the template so that user can define his own event. I think I could use inheritance, let me rethink this for awhile.


Hmm, I'd be surprised if you really need templates then. Off the top of my head.....


I didn't really read through the original post; my bad! I would definately agree though; for the event system you should probably use something similar to what joanusdemntia has stated above. Overloading all your methods that you are going as a base; and then throwing them into an array of the basetype Event. Just poll them by the basetype's virtuals.
-John "bKT" Bellone [homepage] [[email=j.bellone@flipsidesoftware.com]email[/email]]

This topic is closed to new replies.

Advertisement