c++ - Array of template objects -


i don't know how resolve problem templates , inheritance.

in code there templated class looks more or less like:

template<typename t> class derived : public base{      t value; public:      derived(t arg) { value=arg; };      t getvalue() { return value;}; };  class base{ }; 

the purpose of base class group array of objects of derived class. parameter t double, float or complex, although int , structs might become useful. (there should several more similar derived classes few additional functions, later.)

i can create such group

base** m = new base*[numelements]; 

and assign elements of derived class them, e.g.:

m[54] = new derived<double>(100.); 

but how can find out 55th element has value 100 later? need like

virtual t getvalue() = 0; 

but t typename of derived class , may different 2 elements of array.

the visitor pattern best bet here. code iterating array has provide "visitor" object knows how handle each of various types.

struct numericvisitor {     virtual void visit(double) = 0;     virtual void visit(int) = 0;     virtual void visit(unsigned char) = 0; };  struct visitable {     virtual void visitvalue(numericvisitor& visitor) = 0; };  template<typename t> class derived : public visitable {      t value; public:      derived(const t& arg) value(arg) {}      void visitvalue(numericvisitor& visitor) { visitor.visit(value); } }; 

now can define visitors each operation want on collection, e.g. convert each element string, different format each type, or store each element file, each type can take different amount of space.


Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -