C ++: is it possible to use dynamic binding with a template parameter?

I have a template function that takes an object function ("functor") as a template parameter:

 template <typename Func> int f (void) {
    Func func;
    return func ();
};

struct Functor {
   virtual int operator () (void) = 0;
};

struct Functor0 : Functor {
    int operator () (void) {
        return 0;
    }
};

struct Functor1 : Functor  {
    int operator ()  (void) {
        return 1;
    }
};

I want to avoid a block if-else, for example:

int a;
if (someCondition) {
    a = f<Functor0> ();
}
else {
    a = f<Functor1> ();
}

Is there a way to use something similar to dynamic binding, for example:

a = f<Functor> (); // I know this line won't compile, it is just an example of what I need

and decide at runtime what type (derived) is passed as a template parameter?

+3
source share
2 answers

Is there a way to use something like dynamic snapping

. . - . , ; ( ) . .

+7

( , ) - -..

Functor* fp[] = { new Functor0(), new Functor1() };

- someCondition .

a = (*fp[someCondition])();

, , ... (, !)

, , if , , , ...

+7

All Articles