Transparent Class Wrapper

M

mike

Ok,
IO want to write a class to wrap around another class, to print to the
screen when the vale is changed. So far I have:


template<class T>
class Tracer
{
T data;
public:

Tracer()
{
cout << "New Tracer:" << T() <<"\n";
data = T();
}

Tracer(const T& t)
{
cout << "New Tracer:" << t<<"\n";
data = t;
}

T& operator=(const T& t)
{
cout << "TracerChanged: " << t<<"\n";
data = t;
}




};


allowing me to write:
Tracer<int> a;
Tracer<int> b = 6;
b = 12;
a=4;

but i can't go the other way around:
int e = a; //Error

Now i seem to remeber an explicit operator, and I googled for it this
morning but no luck??
Any thoughts would be apprieciated!

Mike
 
G

Gernot Frisch

mike said:
Ok,
IO want to write a class to wrap around another class, to print to
the
screen when the vale is changed. So far I have:


template<class T>
class Tracer
{
T data;
public:

Tracer()
{
cout << "New Tracer:" << T() <<"\n";
data = T();
}

Tracer(const T& t)
{
cout << "New Tracer:" << t<<"\n";
data = t;
}

T& operator=(const T& t)
{
cout << "TracerChanged: " << t<<"\n";
data = t;
}




};


allowing me to write:
Tracer<int> a;
Tracer<int> b = 6;
b = 12;
a=4;

but i can't go the other way around:
int e = a; //Error

Now i seem to remeber an explicit operator, and I googled for it
this
morning but no luck??
Any thoughts would be apprieciated!


operator T() {return data;}

HTH,
-Gernot
 
M

Mike Wahler

mike said:
Ok,
IO want to write a class to wrap around another class, to print to the
screen when the vale is changed. So far I have:



template<class T>
class Tracer
{
T data;
public:

Tracer()
{
cout << "New Tracer:" << T() <<"\n";
data = T();
}

Tracer() : data(T())
{
cout << "New Tracer:" << data << '\n';
}
Tracer(const T& t)
{
cout << "New Tracer:" << t<<"\n";
data = t;
}

Tracer(const T& t) : data(t)
{
cout << "New Tracer:" << t << '\n';
}
T& operator=(const T& t)
{
cout << "TracerChanged: " << t<<"\n";
data = t;

return data = t;

operator T() const
{
return data;
}
};


allowing me to write:

int main()
{
Tracer<int> a;
Tracer<int> b = 6;
b = 12;
a=4;

but i can't go the other way around:
int e = a; //Error

return 0;
}
Now i seem to remeber an explicit operator, and I googled for it this
morning but no luck??
Any thoughts would be apprieciated!

What you were looking for is 'conversion operator'.

-Mike
 
G

Gernot Frisch

mike said:
Thanks, thats the ticket!
Mike

Ooops! Forgot the "const" at the end:
operator T() const {return data;}

otherwise you might get stange errors some day...
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top