Q:

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

I have a template function which accepts a function-object ('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 an if-else block like:
int a;
if (someCondition) {
    a = f<Functor0> ();
}
else {
    a = f<Functor1> ();
}

Is there a way to use something similar to dynamic binding, i.e something like:
a = f<Functor> (); // I know this line won't compile, it is just an example of what I need

and decide in runtime what (derived) type is passed as the template parameter?

A:

Is there a way to use something similar to dynamic binding

No. This is fundamentally impossible. At some point in your code you need to have the case distinction. Of course, that doesn’t have to be written manually; you can use macros (or again templates) to generate the necessary code. But it needs to be there.

A:

One way to avoid the check (if that is REALLY what you want to do), is to use an array - ..
Functor* fp[] = { new Functor0(), new Functor1() };

now - use someCondition as an index.
a = (*fp[someCondition])();

this relies simply on run-time polymorphism rather than the redundant template mechanism you are using... (btw. don't forget to cleanup!)
Of course, this is nasty and frankly redundant, the overhead of the if will be insignificant, but the clarity it adds to the code is significant...

