c++: override template member function in parent class -
let's suppose have such structure of classes: base class object
, parent class bool
, int
, float
, bytes
, unicode
classes. before had functions bool cast_bool() const
, int cast_int() const
, etc. virtual functions in object
class , in child classes i've implemented these functions separately.
it seems better solution implement template <typename type> type cast() const
function instead. however, since c++ prohibits virtual template functions don't know how can complete task. need provide template <typename type> type cast() const
object
, childs. generic object::cast<type>() const
throw casterror
; every type bool
, int
, etc. i'll implement functions bool::cast<bool>() const
, int::cast<bool>() const
, etc. i'm planning add cast builtin objects, though overload operator bool() const
, operator signed short() const
, etc. if there no implementation, template must switch generic form object
class, throwing error. there way (perhaps need use pattern)? or easier leave functions int cast_int() const
? in advance!
add intermediate class in example below or use dynamic_cast
without template methods.
#include <iostream> #include <string> using namespace std; template <class> class objectimpl; class object { public: virtual ~object() {} template <class t> t cast() const { if (auto obj = dynamic_cast<const objectimpl<t>*>(this)) { return obj->cast(); } else { throw std::string("cast error"); } } }; template <class t> class objectimpl : public object { public: virtual t cast() const = 0; }; class bool : public objectimpl<bool> { public: bool cast() const override { return true; } }; class float : public objectimpl<float> { public: float cast() const override { return 12.34f; } }; int main() { object* obj = new float; cout << obj->cast<float>() << endl; try { cout << obj->cast<bool>() << endl; } catch (std::string e) { cout << e << endl; } return 0; }
Comments
Post a Comment