how to construct a class with member type unknown till runtime?

C

ckpun1978

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
 
R

Rolf Magnus

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.
 
C

ckpun1978

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
 
R

red floyd

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;
 
M

manu

template <class T>
class myfirst
{
public:

private:
Array<T> myarray;
void * runtime_change_member;
};

You may use something like Boost.Any, Boost.Variant.
 

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

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,119
Latest member
IrmaNorcro
Top