c++ - "template polymorphism" when calling function for templated parameter of base type, with derived type? -


i've got template class:

template <class t> class templateclass {    //irrelevant class } 

and 2 classes, 1 base , 1 class derives it:

class base {     //does whatever }  class derived : public base { } 

now want assemble function can deal templateclass of templated type base* templateclass of templated type derived* without having implement function separately both types.

in code, i'd able do:

void dosomething(const templateclass<base *> &tc) {    //do } 

and somewhere else in code:

templateclass<base *> a; templateclass<derived *> b;  dosomething(a); //works dosomething(b); //doesn't work, i'd work 

is there way implement without having manualy overload dosomething derived* ?

sadly, c++ not support template covariance, cannot automatically. workaround, this:

template <typename t> void dosomething(const templateclass<t*>& tc) {     // in c++03, use boost_static_assert , boost::is_convertible     static_assert(         std::is_convertible<t*, base*>::value,         "template argument must convertible base*"     );      // ... } 

demo on ideone.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -