| Topic: |
DEVELOP > c-Plus-Plus |
| User: |
"" |
| Date: |
04 Sep 2005 07:01:10 PM |
| Object: |
how to construct a class with member type unknown till runtime? |
Hi,
I am now writing a class using template. I run into a situation
that, one of my member type is not unknown until run-time (but i dont'
want to specify a template entry for it). How should I handle this?
template <class T>
class myfirst
{
public:
private:
Array<T> myarray;
void * runtime_change_member;
};
Thanks,
Carson
.
|
|
| User: "Rolf Magnus" |
|
| Title: Re: how to construct a class with member type unknown till runtime? |
04 Sep 2005 07:16:24 PM |
|
|
wrote:
Hi,
I am now writing a class using template. I run into a situation
that, one of my member type is not unknown until run-time (but i dont'
want to specify a template entry for it). How should I handle this?
Derive them all from a polymorphic base class. Then use a pointer to that
base class in your class template.
.
|
|
|
| User: "" |
|
| Title: Re: how to construct a class with member type unknown till runtime? |
04 Sep 2005 07:48:12 PM |
|
|
but if I use pointer to refer, how can I know which type I should cast
to? (cos' i don't know the base class type, as it is polymorphic?)
Carson
.
|
|
|
| User: "red floyd" |
|
| Title: Re: how to construct a class with member type unknown till runtime? |
04 Sep 2005 08:19:53 PM |
|
|
wrote:
but if I use pointer to refer, how can I know which type I should cast
to? (cos' i don't know the base class type, as it is polymorphic?)
Carson
That's what virtual functions are for.
class Shape {
public:
virtual void Draw() = 0;
};
class Circle : public Shape {
public:
void Draw() {
// draw a circle;
}
};
class Rectangle : public Shape {
public:
void Draw() {
// draw a rectangle
}
};
class Polygon : public Shape {
public:
void Draw() {
// guess what this is supposed to do
}
};
template <class T>
class myfirst
{
public:
private:
Array<T> myarray;
void * runtime_change_member;
};
myfirst<Shape*> struct;
.
|
|
|
|
|
|
| User: "manu" |
|
| Title: Re: how to construct a class with member type unknown till runtime? |
05 Sep 2005 04:37:21 AM |
|
|
On Mon, 05 Sep 2005 04:01:10 +0400, <ckpun1978@gmail.com> wrote:
template <class T>
class myfirst
{
public:
private:
Array<T> myarray;
void * runtime_change_member;
};
You may use something like Boost.Any, Boost.Variant.
.
|
|
|
|

|
Related Articles |
|
|