Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call the unspecialized version of a function when specializing it in C++?

Say I have a templated class:

template <typename T>
class foo {
  void do_someting(T obj) {
    // do something generic...
  }
};

and I want to specialize do_something, but within it I want to call the "normal" do_something function:

template<>
void foo<MyObj>::do_something(MyObj obj) {
  // do something specific...
  // and ALSO do something generic!
}

is there a way to refer to the normal version of do_something within my specialized function? Or do I just have to copy the code?

(I know that I could refactor foo in such a way that I wouldn't have this exact problem, but as it happens I can't really modify the "real" foo, as it's heavily-shared code.)

like image 303
Jacob B Avatar asked Nov 04 '10 17:11

Jacob B


1 Answers

No. Your specialization is the only definition that will exist for the MyObj type argument. But, consider modifying the foo template in this manner, which will be transparent to the current users of the template:

template<typename T>
class foo {
  void prelude(T &obj){ // choose a better name
    /* do nothing */
  }
  void do_something(T obj){
    prelude(obj);
    // do something generic...
  }
};

Then define a specialization for the prelude:

template<>
void foo<MyObj>::prelude(MyObj &obj){
  // do something specific
}

This is somewhat similar in structure to the main use case for private virtual members. (Sort of. Not really. But it's what inspired me in this answer.)

like image 192
Steve M Avatar answered Oct 04 '22 01:10

Steve M