STL and some Template

T

Tony Johansson

Hello!

Here I have two classes these are called Handle and Body and a main. You
have the class definition below. Some basic information. In the Handle class
is there a pointer to the Body class.
Each Body object contains one primitive datatype int.
The Body instance is created in the constructor for Handle. In main I
instanciate some Handle object and use the STL function push_front to push
these object into the list.

In main I also use the STL function for_each to access each node in the list
as you see here for_each(myList1.begin(), myList1.end(),
Handle<Integer>());

The last parameter is calling the functionsoperator defined in class Handle
for each node in the list.
In my case I have two nodes so this functionsoperator is called two times so
the text testing is printed two times. This works

The only way to get the primitive int values from the Body class is to use
the
type conversion operator defined as this
operator int() const
{ return this->value_; }
which convert from class Body to an int.

But now to my question how do I do if I want to display the entire list
myList1 with all the ints that exist in each created body object. I want to
check that my push_front is doing what I expect it to do.
So have anybody out there any suggestion how to access the type conversion
operator in class Body
to get the primitive int defined there.

I know that I must add destructor, copy constuctor and assignment operator
and all that stuff.

//Tony

Main
*******
include "handle.h"
#include <list>
#include <algorithm>
using namespace std;

int main()
{
list <Handle <Body> > myList1;

Handle<Body> myh1(1);
myList1.push_front(myh1);
Handle<Body> myh2(2);
myList1.push_front(myh2);

for_each(myList1.begin(), myList1.end(), Handle<Integer>());

return 0;
}

Handle
*******
#include "body.h"
#include <iostream>
using namespace std;
template<class T>
class Handle
{
public:
Handle(int value)
{ body = new T(value); }

void operator()(Handle<T>& temp)
{ cout << "testing" << endl; }

private:
Body *body;
};


#include <iostream>
class Body
{
public:
Body() {}

Body(int value): value_(value) {}

operator int() const
{ return this->value_; }
private:
int value_;
};


//Tony
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top