我有一个模板函数,它接受一个function-object ('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;
}
};我想要避免像这样的if-else块:
int a;
if (someCondition) {
a = f<Functor0> ();
}
else {
a = f<Functor1> ();
}有没有一种方法可以使用类似于动态绑定的东西,比如:
a = f<Functor> (); // I know this line won't compile, it is just an example of what I need并在运行时决定将什么(派生的)类型作为模板参数传递?
发布于 2011-05-09 19:39:23
有没有一种类似于动态绑定的方法
不是的。这基本上是不可能的。在代码中的某些地方,您需要区分大小写。当然,这不需要手动编写;您可以使用宏(或模板)来生成必要的代码。但它必须在那里。
发布于 2011-05-09 19:57:50
避免检查的一种方法(如果这确实是您想做的)是使用一个数组- ..
Functor* fp[] = { new Functor0(), new Functor1() };现在-使用someCondition作为索引。
a = (*fp[someCondition])();这仅仅依赖于运行时多态性,而不是您正在使用的冗余模板机制……(顺便说一下。别忘了清理一下!)
当然,这是令人讨厌的,坦率地说是多余的,if的开销将是微不足道的,但它为代码增加的清晰度是重要的……
https://stackoverflow.com/questions/5936318
复制相似问题