C++:是否可以将动态绑定与模板参数一起使用?

Ita*_*atz 3 c++ inheritance templates

我有一个模板函数,它接受一个函数对象('functor')作为模板参数:

 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;
    }
};
Run Code Online (Sandbox Code Playgroud)

我想避免if-else像这样的块:

int a;
if (someCondition) {
    a = f<Functor0> ();
}
else {
    a = f<Functor1> ();
}
Run Code Online (Sandbox Code Playgroud)

有没有办法使用类似于动态绑定的东西,例如:

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

并在运行时决定将(派生)类型作为模板参数传递?

Kon*_*lph 7

有没有办法使用类似于动态绑定的东西

不,这根本不可能.在代码中的某些时候,您需要区分大小写.当然,这不必手动编写; 您可以使用宏(或再次模板)来生成必要的代码.但它需要在那里.


Nim*_*Nim 7

避免检查的一种方法(如果真的是你想要做的)是使用数组 - ..

Functor* fp[] = { new Functor0(), new Functor1() };
Run Code Online (Sandbox Code Playgroud)

现在 - someCondition用作索引.

a = (*fp[someCondition])();
Run Code Online (Sandbox Code Playgroud)

这仅仅依赖于运行时多态性而不是你正在使用的冗余模板机制......(顺便说一句.别忘了清理!)

当然,这是令人讨厌和坦率的多余,这if将是无关紧要的开销,但它增加代码的清晰度是重要的...