How to mimic polymorphism in classes with template methods (c++)?

Posted by davide on Stack Overflow See other posts from Stack Overflow or by davide
Published on 2012-09-07T15:36:52Z Indexed on 2012/09/07 15:37 UTC
Read the original article Hit count: 207

Filed under:
|
|

in the problem i am facing i need something which works more or less like a polymorphic class, but which would allow for virtual template methods.

the point is, i would like to create an array of subproblems, each one being solved by a different technique implemented in a different class, but holding the same interface, then pass a set of parameters (which are functions/functors - this is where templates jump up) to all the subproblems and get back a solution.

if the parameters would be, e.g., ints, this would be something like:

struct subproblem
{
...
virtual void solve (double& solution, double parameter)=0; 
}
struct subproblem0: public subproblem
{
...
virtual void solve (double& solution, double parameter){...}; 
}
struct subproblem1: public subproblem
{
...
virtual void solve (double* solution, double parameter){...}; 
}

int main{
subproblem problem[2];
subproblem[0] = new subproblem0();
subproblem[1] = new subproblem1();
double argument0(0),
       argument1(1),
       sol0[2],
       sol1[2];
for(unsigned int i(0);i<2;++i)
    {
    problem[i]->solve( &(sol0[i]) , argument0);
    problem[i]->solve( &(sol1[i]) , argument1);
    }
return 0;
}

but the problem is, i need the arguments to be something like

Arg<T1,T2> argument0(f1,f2)

and thus the solve method to be something of the likes of

template<T1,T2> solve (double* solution, Arg<T1,T2> parameter)

which cant obviously be declared virtual ( so cant be called from a pointer to the base class)...

now i'm pretty stuck and don't know how to procede...

© Stack Overflow or respective owner

Related posts about c++

Related posts about templates