c++ - Call function of template class created at runtime -


i have tricky question c++(11) template classes , instantiation types determined @ runtime:

following scenario: user defines type of template class using config file (ros parameters). determines type of template class, not further logic:

class definition:

template<typename t> class myclass {     //[...] } 

exemplary code:

/* [read parameter , write result bool use_int] */  std::unique_ptr<myclass> myclassptr {nullptr}; if(use_int) {     myclassptr.reset(myclass<int>); } else {     myclassptr.reset(myclass<double>); }  myclassptr->foobar();  /* [more code making use of myclassptr] */ 

so code (of course) not compiling, because unique_ptr template must specified template type. however, problem arises template type must same objects assigned using reset.

one ugly solution copy code myclassptr->foobar(); , following each branch of if/else, don't like.

i see solution similar this:

/* [read parameter , write result bool use_int] */  myclass<use_int ? int : double> myclass; myclass.foobar(); 

what have read far not possible.

does have nice solution this?

the simplest way is:

class iclass{   virtual ~iclass {}   virtual void foobar()=0; }; template<typename t> class myclass:public iclass { public:   void foobar() override {     // code here   } }; std::unique_ptr<iclass> myclassptr {}; if(use_int) {   myclassptr.reset(new myclass<int>()); } else {   myclassptr.reset(new myclass<double>()); } myclassptr->foobar(); 

boost::variant solution, used unrelated types. type erasure done, again done when have unrelated types want impose uniform interface on.

in other languages generics sort of templates, abstract interface auto-generated typecasting , typechecking added. c++ templates function or class compile time factories. 2 outputs of such factories unrelated @ runtime default, , can add such relations if want.


Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -