c++ - Returning a Generic container from a Set of Dictionaries -


i have collection of dictionaries (std::maps) store generic containers foo unique id. given such unique id, return corresponding container. not know before hand in dict foo object given id stored, along line of following:

#include <map>  std::map<id, foo<double>> mapdouble; std::map<id, foo<int>>    mapint;   template <class t> foo<t> getval(id id) {      std::map<id, foo<double>>::iterator itdoub = mapdouble.find(id);     if(itdoub != mapdouble.end()) {        return = itdoub->second;     }       std::map<id, foo<int>>::iterator itint = mapint.find(id);     if(itint!= mapint.end()) {        return = itint->second;     } }   void bar() {     foo<int> foo getval<int>(3); } 

but following error message

error: no viable conversion 'foo <double>' 'foo <int>' 

which of course makes complete sense. correct way of implementing functionality? guess implementing here sort of factory.

your problem there no nice connection between type parameter (<int>), , member name (mapint).

the solution find way not use member - simplest is:

#include <map>  typedef int id; template <typename t> struct foo {};  class mapcontainer {     std::map<id, foo<double>> mapdouble;     std::map<id, foo<int>>    mapint;      template <typename t> std::map<id, foo<t>>& getmap();  public:     template <class t>     foo<t> getval(id id) {         auto &map = getmap<t>();         auto = map.find(id);         if(it != map.end()) {             return it->second;         } else {             return foo<t>{}; // ???         }     } };  template <> std::map<id, foo<double>>& mapcontainer::getmap() { return mapdouble; } template <> std::map<id, foo<int>>& mapcontainer::getmap() { return mapint; } 

here, connection between type , member name handled template method specializations (getmap).


note gives linker error unsupported types. can friendlier error message defining generic getmap such fails on instantiation.

a fiddlier perhaps more satisfying solution (that scales , generalizes better more types) eliminate named data members entirely, , use generic type-to-container lookup instead. example, tuple of maps can interrogated element type instead of position (see modern c++ design/loki), , boost.fusion provides heterogeneous sets want.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -