i'm trying replace virtual functions on templates:
struct derived1; struct derived2; template <typename t> struct base { void f(); }; template<> void base::f<derived1>(){std::cout<<"derived1\n";} template<> void base::f<derived2>(){std::cout<<"derived2\n";} struct derived1 : public base {}; struct derived2 : public base {};
it works until create container of pointers:
std::vector<base*> vec;//doesn't work - needs explicit parameter base vec.push_back(new derived1); vec[0]->f();//call f() derived1
is possible rid of "virtuality" in case?
virtual
function dispatch can determine runtime dynamic type of object before selecting function call. templates cannot that, because resolved @ compile time. if have base *
, no template recall derived type initialized from.
slightly off topic, function template specialization idea. overloads more flexible because compiler has mechanism select overload best fits particular function call. explicit specializations not create overloads, alter behavior of pre-existing general template. least flexible way ask dispatch.
Comments
Post a Comment