c++ - How to make an vector of abstract template class -


following not work:

std::vector<irule*> vec; rulerangedouble *rule = new rulerangedouble(0, 100); vec.push_back(rule); 

now how can make vector of different rules? know, have use pointers... else have working? how can change base structure work?

i use interface following:

// interface     template <typename t>     class irule     {         public:             virtual bool isvalid(t value) = 0;     }; 

and example class looks this:

class rulerangedouble : public irule<double>     {         private:             double min;             double max;         public:              bool isvalid(double value)             { ....             };     }; 

you can implement getbestvalidvalue()in several ways. 1 define special general (but non-template) return type used getbestvalidvalue() , argument type isvalid(value) (juanchopanza's answer faulty here):

class valuetype {   enum { is_int, is_double } my_type;  // add more if want   union { my_int; my_double; };        // union works simple types public:   // implicit construction allowed types   valuetype(int x) : my_type(is_int), my_int(x) {}   valuetype(double x) : my_type(is_double), my_double(x) {}   // use sfinae is<type>() function   template<typename t>   typename std::enable_if<std::is_same<t,int>::value,bool>::type   is() const { return my_type==is_int; }   template<typename t>   typename std::enable_if<std::is_same<t,double>::value,bool>::type   is() const { return my_type==is_double; }   // implicit type conversion allowed types   // note: not assert(is<t>())   operator int() { return my_int; }   operator double() { return my_double; } };  class irule { public:   virtual bool isvalid(valuetype const&) const = 0; // fixed bug in juanchopanza's answer   virtual valuetype getbestvalidvalue() const = 0;  // return type of value   virtual ~irule() {} };  template<typename t> class rule : public irule { protected:   virtual bool valid(t) const = 0;    virtual t bestvalidvalue() const = 0; public:   bool isvalid(valuetype const&value) const   {     return value.is<t>()         && valid(value);         // implicit type conversion t   }   valuetype getbestvalidvalue() const   {     return bestvalidvalue();     // implicit construction of valuetype   }   .... } 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -