c++ - Storing templated derived classes in container -


i have series of field validators each following:

template <typename t> class namevalidator : public validator<t> {      ...     bool validate(const t& msg) const override { ... }     ...  }; 

each of these validators must able validate different message types, hence template parameter t.

i create manager class serves common gateway each of these validators. following:

class validatormanger {      ...     // calls validate() functions each field.     template <typename t>     bool validate(const t& msg) { ... }     ...  }; 

hence, need store each of validator classes (ex: namevalidator<t>) in type of data structure , iterate on them within validatormanager::validate().

is there way not have explicitly specialize templates each message type? i'm imaging following

validator_map.insert(std::make_pair("name", namevalidator<t>)); validator_map.insert(std::make_pair("age", agevalidator<t>()); ... 

though gibberish.

questions:

  • has used sort of pattern before , have solution achieving this?
  • should rethinking design entirely?

if want container can food instructions

validator_map.insert(std::pair("name", namevalidator<t>())); validator_map.insert(std::pair("age", agevalidator<t>())); 

you need type t known, othewise namevalidator<t> isn't type , namevalidator<t>() can't initialize object.

so suppose validator_map should variable (static?) inside template validator() method in validatormanager.

so, hoping can semplified, best can imagine in following example

#include <set> #include <vector> #include <memory> #include <iostream>  template <typename t> struct validator   { virtual bool validate (t const &) const = 0; };  template <typename t> struct namevalidator : public validator<t>  {    bool validate (t const & msg) const override     { std::cout << "- name (" << msg << ")" << std::endl; return true; }  };  template <typename t> struct agevalidator : public validator<t>  {    bool validate (t const & msg) const override     { std::cout << "- age  (" << msg << ")" << std::endl; return true; }  };  struct validatormanager  {    template <typename t>    bool validate (t const & msg) const     {       static bool first {true};       static std::vector<std::unique_ptr<validator<t>>> vvt;        if ( first )        {          vvt.emplace_back( new namevalidator<t>{} );          vvt.emplace_back( new agevalidator<t>{} );           first = false;        }        bool ret { true };        ( auto const & v : vvt )          ret &= v->validate(msg);        return ret;     }  };  int main()  {    validatormanager  vm;     vm.validate(1);    vm.validate(2.2);    vm.validate("3.3");  } 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -