Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override virtual method with template method [duplicate]

Possible Duplicate:
Can a member function template be virtual?

In a base class, the function my_func is defined as virtual. However, in the derived class I would like to have my_func to be a template method. Is this possible?

It seems it isn't. I get the error "cannot allocate an object of abstract type", which I believe it is related to the fact that the compiler does not acknowledge the override of the virtual my_func in the base class. Does this reveal a poor design maybe?

Thanks a lot.

UPDATE: Thanks for the answers. Some of you are suggesting I should post some of the code, so here it is. In the base class:

virtual void Fill(EventInfo* info, EasyChain* tree, vector<Muon*>& muons, vector<Electron*>& electrons, vector<Jet*>& jets, LorentzM& met) = 0;

But in the derived class I would like to have:

template<typename _Jet> 
void Fill(EventInfo* info, EasyChain* tree, vector<Muon*>& muons_in, vector<Electron*>& electrons_in, vector<_Jet>& jets_in, LorentzM& met){

From your answers, I understand that a solution to the problem would be to define another function in the derived class:

void Fill(EventInfo* info, EasyChain* tree, vector<Muon*>& muons, vector<Electron*>& electrons, vector<Jet*>& jets, LorentzM& met){
//
}

but then, this function and the template function are the same for the case of _Jet being Jet*, wouldn't that be a problem as well?

Some have suggested a design problem here, I guess that's true, I'll have to think about how to go around this then.

like image 955
elelias Avatar asked Dec 11 '12 10:12

elelias


1 Answers

Your templated method overloads the original (same name but different parameters). You still have to override the original as well, to make your derived class non-abstract. You can do both no problem, so you will have two versions of the method in the derived class, just be careful and conscious of which one will get called...

You can then make the overriden overload version of method to call the new template overload version. This may or may not do what you want to achieve, depending on what you want to achieve...

It might still be better for the template method to have a different name, to avoid confusion, because you can not call it directly anyway, unless you have pointer of the derived class type. If you have pointer to the abstract base class, you must call the method with the parameters defined there, even if it is virtual method and a derived class method is what actually gets called.

like image 146
hyde Avatar answered Oct 07 '22 13:10

hyde