c++ - Alternative for virtual template functions -
c++ - Alternative for virtual template functions -
i have abstract ui
class needs able inquire user input. function templated because different things can asked for.
however, function must virtual because want derived classes of ui
able provide own implementations (a commandlineui
need behave differently webbasedui
).
class ui { // ... public: // inquire input template<t> virtual t askfor(const std::string& mesg) const = 0; // inquire provide default fallback template<t> virtual t askfor(const std::string& mesg, const t& def) const = 0; } class commandlineui : ui { // ... public: template<t> virtual t askfor(const std::string& mesg) const { // implementation details } template<t> virtual t askfor(const std::string& mesg, const t& def) const { // implementation details } }
the above code not work however, since templated method cannot virtual in c++, reasons go above me.
i read things visitor pattern or type erasure beingness able prepare problem, fail see how. (i tried translate examples found in answers similar stack overflow questions wasn't successful).
in case, standard extremely straightforward
§14.5.2.3) fellow member function template shall not virtual. [ example:
template <class t> struct aa { template <class c> virtual void g(c); // error virtual void f(); // ok };
— end example ]
basically, how implement them? vtable like?
if need type "in-streamable", i'd recommend checking out boost.typeerasure library. may not solve problem, it's pretty neat. you'll need like:
using inputable = any< mpl::vector< copy_constructible<>, typeid_<>, istreamable<> > >; virtual inputable askfor(const std::string& mesg) const = 0;
probably more involved that, i've played around library makes possible have virtual "template" fellow member function long define need template type do. (note there's any_cast
caller knows type wants get, can cast result it.)
c++ templates inheritance polymorphism virtual
Comments
Post a Comment