473,387 Members | 1,882 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Problem: how to use one std container to store multiple types?

Hi.
Before all, please excuse me for bad english and for very newbie
questions. I hope to don't boring you.

I'm trying to write a very simple GUI using openGL.
So I'm writing some different widgets classes, like buttons, images,
slider, etc...

Each class has a draw() method.

The idea is to put all widget to draw in a vector, and after, in pseudocode:

-----------------------------
for each widget w in vector:
w.draw()
-----------------------------

So I should declare the vector, like

vector<widget> widgetList;

and this is my trouble: I've different classes (that has some common
methods, like draw(), on(), off() etc...) and I should put all in one
std container. It's possible?
Really I don't know even how to declare the vector. In example, if I've
the class

----------------------------
class foo {
private:
int width;
int height;
public:
int getWidth();
int getHeight();
};
----------------------------

how to declare a container for foo? Surely not writing

vector<foo> fooList;

Should I use typedef? Can you explain me this?

I know I'm a newbie and maybe these are very silly questions. However I
can't find these info on the books I'm reading (they are for beginners,
and don't write about STD) and the same using google.
Can you help me?

Thanks,
Manuel

Dec 27 '05 #1
20 5071
Manuel wrote:

I'm trying to write a very simple GUI using openGL. So I'm writing
some different widgets classes, like buttons, images, slider, etc...

Each class has a draw() method.

The idea is to put all widget to draw in a vector, and after, in
pseudocode:

----------------------------- for each widget w in vector: w.draw()
-----------------------------

Look at Design Pattern called Composite which can be used to wrap such
structure easily. GoF's book [1] includes case study very similar to
your problem so you may find this book intersting.

Simply, create abstract base class i.e. Widget and
inherit concrete (specialized) gadgets from the Widget.
Declare in Widget pure virtual method i.e. void draw(canvas)
and implement it in every concrete widget suitably.
Finally, store all widgets in a container through pointer to the base
class Widget (dynamic polymorphism).

So I should declare the vector, like

vector<widget> widgetList;

and this is my trouble: I've different classes (that has some common
methods, like draw(), on(), off() etc...) and I should put all in
one std container. It's possible?


Yes, do it as I explained above.
Here is simple implementation which should help to understand that idea:

#include <algorithm>
#include <iostream>
#include <vector>
////////////////////////////////////////////////////////////
struct DeleteObject
{
template <typename T>
void operator()(const T* ptr) const
{
delete ptr;
}
};
////////////////////////////////////////////////////////////
class Widget
{
public:
virtual void draw() const = 0;
virtual ~Widget() {}
};
class Button : public Widget
{
public:
void draw() const { std::cout << "Drawing Button" << std::endl; }
};
class Label : public Widget
{
public:
void draw() const { std::cout << "Drawing Label" << std::endl; }
};
class Slider : public Widget
{
public:
void draw() const { std::cout << "Drawing Slider" << std::endl; }
};

int main()
{
std::vector<Widget*> v;
v.push_back(new Button());
v.push_back(new Label());
v.push_back(new Slider());
v.push_back(new Button());

std::vector<Widget*>::const_iterator it;
for (it = v.begin(); it != v.end(); ++it)
{
(*it)->draw();
}

// Delete widgets
std::for_each(v.begin(), v.end(), DeleteObject());

return 0;
}
////////////////////////////////////////////////////////////

[1] Design Patterns: Elements of Reusable Object-Oriented Software
by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides

Cheers
--
Mateusz Łoskot
http://mateusz.loskot.net
Dec 27 '05 #2
Mateusz Łoskot wrote:
Look at Design Pattern called Composite which can be used to wrap such
structure easily. GoF's book [1] includes case study very similar to
your problem so you may find this book intersting.

Simply, create abstract base class i.e. Widget and
inherit concrete (specialized) gadgets from the Widget.
Declare in Widget pure virtual method i.e. void draw(canvas)
and implement it in every concrete widget suitably.
Finally, store all widgets in a container through pointer to the base
class Widget (dynamic polymorphism).


Thanks you very much for the example!!

Some questions:

1) What happen if I use v.clear() instead DeleteObject() ??
2) In your example each class has the same number of methods. But what
happen if some classes have different numbers of methods? Should be not
a problem, right ??
3) Exist other way instead using a pointer in std::vector<Widget*> v; ??

Again, thanks, THANKS!

Ciao,

Manuel
Dec 27 '05 #3
Manuel wrote:

Thanks you very much for the example!!

You're welcome!
Some questions:

1) What happen if I use v.clear() instead DeleteObject() ??
Look at older thread titled "STL map and memory management (clear() )",
about Dec, 15.
2) In your example each class has the same number of methods. But
what happen if some classes have different numbers of methods? Should
be not a problem, right ??
No problem. But remember that only common members may be accessed during
iterations (without casting). I mean, when iterating you "can see" all
widgets "through" base class interface - Widget.
Just a figurative explanation :-)
3) Exist other way instead using a pointer in std::vector<Widget*> v;
??


In your particular solution I don't see anything better - abstract base
class allow you to access specialized types through unified interface
(declared in base class). I strongly recommend you to read GoF's
explanation of Composite, then may be you will get the idea behind it
more clear.

Note: you can use "smart pointers" instead of raw pointers. Then memory
management is much simplier. Here they are:
http://www.boost.org/libs/smart_ptr/smart_ptr.htm

Cheers
--
Mateusz Łoskot
http://mateusz.loskot.net
Dec 27 '05 #4
Mateusz Łoskot wrote:
You're welcome! [...] Look at older thread titled "STL map and memory management (clear() )",
about Dec, 15. [...]I strongly recommend you to read GoF's
explanation of Composite, then may be you will get the idea behind it
more clear.

Note: you can use "smart pointers" instead of raw pointers. Then memory
management is much simplier. Here they are:
http://www.boost.org/libs/smart_ptr/smart_ptr.htm

THANKS!!
I'll study your suggestions and trying some experiments before boring
you with other newbie questions.:-)

Best Regards,

Manuel
Dec 27 '05 #5

Manuel wrote in message <43**********************@reader1.news.tin.it>.. .
Mateusz Łoskot wrote:
Some questions:

1) What happen if I use v.clear() instead DeleteObject() ??


You would leave objects in memory with no way to delete them. If you want to
use 'v.clear()', you can do it this way:

int main(){
std::vector<Widget*> v;
Button Btn;
v.push_back( &Btn );
Label Lbl;
v.push_back( &Lbl );
// .... etc. ....
std::vector<Widget*>::const_iterator it;
for (it = v.begin(); it != v.end(); ++it){
(*it)->draw();
}

v.clear() // vector will empty at this point.
Label Lbl2;
v.push_back( &Lbl2 );
v.clear() // vector will empty at this point.
return 0;
} // Btn, Lbl, etc. destructors will be invoked at this point.

Also read what Mateusz suggested.

Bruce Eckel, in his book 'Thinking in C++' vol 2, has another way to handle
the pattern (which he calls the 'Command pattern' ). You can download a legal
copy of the book here: http://www.bruceeckel.com/ [ref: //:
C10:CommandPattern.cpp ]

--
Bob R
POVrookie
Dec 27 '05 #6
BobR wrote:
Bruce Eckel, in his book 'Thinking in C++' vol 2, has another way to handle
the pattern (which he calls the 'Command pattern' ). You can download a legal
copy of the book here: http://www.bruceeckel.com/ [ref: //:
C10:CommandPattern.cpp ]

Thanks...a lot of things to read :-)

POVrookie


Curiosity: Are you POVray user?

Ciao,

Manuel
Dec 27 '05 #7

Manuel wrote:
Mateusz Loskot wrote:
You're welcome!

[...]
Look at older thread titled "STL map and memory management (clear() )",
about Dec, 15.

[...]
I strongly recommend you to read GoF's
explanation of Composite, then may be you will get the idea behind it
more clear.

Note: you can use "smart pointers" instead of raw pointers. Then memory
management is much simplier. Here they are:
http://www.boost.org/libs/smart_ptr/smart_ptr.htm

THANKS!!
I'll study your suggestions and trying some experiments before boring
you with other newbie questions.:-)


I recommend you use a deep copy (clone) smart pointer, instead.
http://code.axter.com/copy_ptr.h
or a COW smart pointer
http://code.axter.com/cow_ptr.h

Both the copy_ptr and the cow_ptr can perform a deep copy when needed.
Example usage:
vector<copy_ptr<foo> > vFoo;
vFoo.push_back(new FooDerived);

You can use the boost::shared_ptr only if you're sure sharing the
pointee will not negatively effect your code. In most cases, this is
rarely what you want in a container.

Boost also has a set of pointer containers, but the interface is poor,
and does not match the STL containers very well.
I recommend using copy_ptr or cow_pt instead.

For more information, read the following related Article:
http://www.codeguru.com/cpp/cpp/algo...le.php/c10407/

In the above article it uses a clone_ptr smart pointer, but the
copy_ptr is a more optimize and complete version of the clone_ptr class.

Dec 27 '05 #8

Manuel wrote in message <43**********************@reader3.news.tin.it>.. .
BobR wrote:
Bruce Eckel, in his book 'Thinking in C++' vol 2, has another way to handle the pattern (which he calls the 'Command pattern' ). You can download a legal copy of the book here: http://www.bruceeckel.com/ [ref: //:
C10:CommandPattern.cpp ]


Thanks...a lot of things to read :-)

POVrookie


Curiosity: Are you POVray user?


Yes. I am still a POVray rookie because I have been spending more time
learning C++.
One of my current projects is for POVray (though it also outputs OGL, RAW,
RAD, OBJ, TIN, RIB). It makes a 3D Rock (as triangle mesh) and
displays/animates in a OpenGL window in wxWidgets.

Some people think that POV is Point-Of-View, and I just answer them with a
smiley-face :-}

--
Bob R
POVrookie
--
POVray: http://www.povray.org/
Dec 27 '05 #9
Can you explain me (please be patient) because this structure

struct DeleteObject
{
template <typename T>
void operator()(const T* ptr) const
{
delete ptr;
}
};

instead a function like

DeleteObject( *ptr){ delete ptr; };

??

Thanks,

Manuel
Dec 28 '05 #10

Manuel wrote:
Can you explain me (please be patient) because this structure

struct DeleteObject
{
template <typename T>
void operator()(const T* ptr) const
{
delete ptr;
}
};

instead a function like

DeleteObject( *ptr){ delete ptr; };


Easy: the function misses a type. Either you fix the type for
'ptr', or you make a function template DeleteObject<T>.

Now, if you want to delete every pointer in the range
container.begin(), container.end(), you need to pass the
correct deleter. The struct can delete all pointer types,
but the function (or an instantiation of the function template)
can delete only one type (in the functio template case,
the type it's instantiated with).

In practice, this means the function form needs a <TYPE>
argument. This may be a complicated expression which
must match exactly the type already known to the compiler.
That's just a game of 'guess what I'm thinking', not useful.

HTH,
Michiel Salters

Dec 28 '05 #11
Manuel wrote:
Can you explain me (please be patient) because this structure

struct DeleteObject
{
template <typename T>
void operator()(const T* ptr) const
{
delete ptr;
}
};

This is a Function Object (Functor) - read about in a book or Web.
Second, it also is a kind of "universal" Functor which can be
specialized to call delete on all types of pointers.
instead a function like

DeleteObject( *ptr){ delete ptr; };


This is a function (not complete definition, type is missing:
void DeleteObject(MyClass *ptr){ delete ptr; };

In the form above, it's (almost) like a specialized version of the
Functor - operates on one and the only one type - specialized with MyClass.

Template version is more flexible, you can use it for every*** type of
pointers in your container - one Functor for all (almost***).
*** - as you can see how delete operator is used then you see that it
can not be used to delete arrays (delete[] pointer_to_array).

Cheers
--
Mateusz Łoskot
http://mateusz.loskot.net
Dec 28 '05 #12
Thanks!
The functors are very advanced features, I must study a lot before fully
understand them...
However thanks to you now I've at least an idea about how the code work.
Thanks,

Manuel
Dec 28 '05 #13
Manuel wrote:
Thanks!
The functors are very advanced features, I must study a lot before fully
understand them...
Yup! They are worth to learn, definitely.
Especially, when you use STL stuff like algorithms.
However thanks to you now I've at least an idea about how the code work.
Thanks,


You're welcome.
Cheers
--
Mateusz Łoskot
http://mateusz.loskot.net
Dec 28 '05 #14
Ehm...I don't understad another error about this topic.
Using the code below:

----------------------------
#include <iostream>
#include <vector>
using namespace std;

class mhwidget {
public:
virtual void draw() const = 0;
};

class square : public mhwidget {
public:
void draw(){cout << "square!";}
};

class MHwindow {
vector<mhwidget*> widgetList;
public:
void addWidget(mhwidget* w) {cout << "added!";}
};

int main (){
MHwindow MHgui;
MHgui.addWidget(new square);
return 0;
}
-----------------------------

The compiler return this error:

In function `int main()':
cannot allocate an object of type `square'
because the following virtual functions are abstract:
virtual void mhwidget::draw() const
Deleting "const" it work...I'm trying to find the reason of this on
various books, but without success...

Ciao!

Manuel
Dec 28 '05 #15
Manuel wrote:
Ehm...I don't understad another error about this topic.
Using the code below:

----------------------------
#include <iostream>
#include <vector>
using namespace std;

class mhwidget {
public:
virtual void draw() const = 0;
};

OK, but most likely you need to add public virtual destructor:
virtual ~mhwidget();
class square : public mhwidget {
public:
void draw(){cout << "square!";}
};


Here is the problem.
Look, this declaration

void draw() const;

is not the same as thisone:
void draw();

The former declares const-member-function, the latter
non-const-member-function.
And this is what your compiler does not like, the confusion :-)
So, you need to define it this way (as a const function):
void draw() const {cout << "square!";}

Cheers
--
Mateusz Łoskot
http://mateusz.loskot.net
Dec 28 '05 #16
Mateusz Łoskot wrote:
The former declares const-member-function, the latter
non-const-member-function.
And this is what your compiler does not like, the confusion :-)
So, you need to define it this way (as a const function):
void draw() const {cout << "square!";}

Ouch!
I'm stupid!
Sorry for !!another!! silly question!
Dec 28 '05 #17
Manuel wrote:
Mateusz Łoskot wrote:
The former declares const-member-function, the latter
non-const-member-function.
And this is what your compiler does not like, the confusion :-)
So, you need to define it this way (as a const function):
void draw() const {cout << "square!";}


Ouch!
I'm stupid!
Sorry for !!another!! silly question!


I'd not say that. Just try to understand what compiler is saying and
what his message means.
Cheers
--
Mateusz Łoskot
http://mateusz.loskot.net
Dec 28 '05 #18
Mateusz Łoskot wrote:
struct DeleteObject
{
template <typename T>
void operator()(const T* ptr) const
{
delete ptr;
}
};

I've not fully understand functors yet.
I'm trying to write a generic container class: can I declare the
structure above into the class, and use it writing

std::for_each(v.begin(), v.end(), container::DeleteObject());

If yes...it work with any vector, even from differents classes?

Thanks,

Manuel
Dec 29 '05 #19
Manuel wrote:
I'm trying to write a generic container class: can I declare the
structure above into the class, and use it writing


This is my experiments:

----------------------------------------------
#include <windows.h>
#include "mhcontainer.h"
#include <iostream>//For debug

struct DeleteObject
{
template <typename T>
void operator()(const T* ptr) const
{
delete ptr;
}
};

//Put widget into container
void MHcontainer::addWidget(mhwidget* w) { widgetList.push_back(w); }

//Draw all widgets
void MHcontainer::drawAll()
{
std::cout << "size: " << widgetList.size();
std::vector<mhwidget*>::iterator it = widgetList.begin();
while(it != widgetList.end())
{
std::cout << "widget!";
(*it++)->draw();
}
}

//Delete all widgets
void MHcontainer::deleteAll()
{
std::for_each(widgetList.begin(), widgetList.end(), DeleteObject());
}
---------------------------------------
where mhcontainer.h is:
---------------------------------------
#include "mhwidget.h"
#ifndef MHCONTAINER_H
#define MHCONTAINER_H

class mhcontainer
{
private:
bool active = 1;
std::vector<mhwidget*> widgetList;

public:
void setOn(){active = 1;}
void setOff(){active = 0;}
void addWidget(mhwidget*);
void drawAll();
void deleteAll();
~mhcontainer(){};
};

#endif //MHWIDGET_H

---------------------------------------

Maybe OK?
Dec 29 '05 #20
Manuel wrote:
Manuel wrote:
I'm trying to write a generic container class: can I declare the
structure above into the class, and use it writing

This is my experiments:

Please, don't consider a lot of minor errors (caps, ";", #include,
etc...) in the code I've just posted. I've write it very quickly, only
to ask if the *idea" is correct.

Sorry for errors,

Manuel
Dec 29 '05 #21

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Merlin | last post by:
Hi Imagine the following classes (A class diagram will help) BASE, A, B, C, D, E, F, G. A, B, C, D, G inherit from BASE. E, F inherit from D.
8
by: Markus Dehmann | last post by:
I defined a base class in order to put heterogeneous values into a standard container: All values that I store in the container are derived from my base class. Now when I iterate over the...
4
by: Leslaw Bieniasz | last post by:
Cracow, 20.09.2004 Hello, I need to implement a library containing a hierarchy of classes together with some binary operations on objects. To fix attention, let me assume that it is a...
5
by: Johan | last post by:
Hi, Hi like to create a linked list with a template class ( see below ). How to make one using the STL container list. I want to create a linked list with different kind of types i.e....
0
by: Lokkju | last post by:
I am pretty much lost here - I am trying to create a managed c++ wrapper for this dll, so that I can use it from c#/vb.net, however, it does not conform to any standard style of coding I have seen....
7
by: jsale | last post by:
I'm currently using ASP.NET with VS2003 and SQL Server 2003. The ASP.NET app i have made is running on IIS v6 and consists of a number of pages that allow the user to read information from the...
21
by: aaragon | last post by:
Hello everyone, I would like to know if there is a way to use the std::map to store different types for one of its two types. That is, I'm trying to use it as: typedef...
16
by: PeterAPIIT | last post by:
Hello all C++ expert programmer, i have wrote partial general allocator for my container. After reading standard C++ library and code guru article, i have several questions. 1. Why...
9
by: raylopez99 | last post by:
Hello all Im trying to get the below to work and cannot get the format right. Its from this example: http://msdn.microsoft.com/en-us/library/8627sbea(VS.71).aspx What it is: Im trying...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.