Inheritance and template function c++ -


i wondering if there pattern/ways inherit template functions ? template functions can not virtual if base class has template function , derived class has same, function of base class called in following example :

struct base {     base() {}     template < typename t >     void do_something(t&  t) const {         t << "base" << std::endl ;     }     };  struct foo : base {     foo() : base () {}     template < typename t >     void do_something(t&  t) const {         t << "foo" << std::endl ;     } };  struct bar : foo {     bar() : foo() {}     template < typename t >     void do_something(t&  t) const {         t << "bar" << std::endl ;     } };   int main(int argc, char** argv) {      base *b = new base() ;     base *f = new foo() ;     base *ba = new bar() ;      b->do_something(std::cout) ;     f->do_something(std::cout) ;     ba->do_something(std::cout) ;      return 0 ; } 

so program print :

base base base 

is there way make program print :

base foo bar 

actually way found doing make static_cast :

... static_cast<foo*>(f)->do_something(std::cout) ; static_cast<bar*>(ba)->do_something(std::cout) ; ... 

is there pattern or elegant way encapsulate cast unnoticeable function call ? replies

you can need splitting function smaller parts, making each part templated if necessary, or virtual if necessary. in example, that's simple as:

struct base {     base() {}     template < typename t >     void do_something(t&  t) const {         t << something_piece() << std::endl ;     }     virtual const char* something_piece() const {         return "base";     } };  struct foo : base {     foo() : base () {}     const char* something_piece() const {         return "foo";     } };  struct bar : foo {     bar() : foo() {}     const char* something_piece() const {         return "bar";     } }; 

it can more complicated that, idea pretty powerful @ combining compile-time , run-time differences.


Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -