c++ - How do use a template object of any type -
code changed below use smart pointers:
i have template class:
class irequest; template<class t> class request : public irequest { public: request(t in) : m_data(in) {} virtual ~request() {} t get() { return m_data; } void set(t in) { m_data = in; } private: t m_data; }
in class have methods:
template<t> void invoke(request<t>& request) { // stuff } std::unique_ptr<irequest> getrequest(int which) { switch(which) { case 1: return std::unique_ptr<irequest>(new request<int>(1)); case 2: return std::unique_ptr<irequest>(new request<bool>(true)); case 3: return std::unique_ptr<irequest>(new request<double>(2.0)); default: throw std::exception(); } } void run() { int type = getrequesttype(); std::unique_ptr<irequest> request = getrequest(type); invoke(*request); }
the problem this, run() method cannot templated, there must 1 or them, , needs able deal type of request receives, getrequesttype() reading value file, can contain type.
the compiler not this, expects request have type in angled brackets, both in run() method, , call invoke(). expects return type of getrequest() have angled brackets.
is there c++ mechanism holding , passing around template object of type?
using smart pointer should invoke stay is, or should change to:
void invoke<irequest& request)
the short answer no. request<int>
, request<double>
different types , request
not type. getrequest
method not valid returning different types in different cases.
one method work around have base class request
inherits, e.g. irequest
. return (smart) pointer irequest
in getrequest method.
note won't able call current methods in templated class cannot specify them virtual functions in base class. move invoke method base class pure virtual function, allowing implemented in templated class.
class irequest { public: virtual ~irequest() { } virtual void invoke() = 0; }; template <typename t> class request : public irequest { public: request(t in) : m_data(in) { } virtual ~request() { } virtual void invoke() { /* stuff */ } private: t m_data; };
Comments
Post a Comment