【发布时间】:2011-05-09 11:36:11
【问题描述】:
我有一个模板函数,它接受一个函数对象('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
并在运行时决定将什么(派生)类型作为模板参数传递?
【问题讨论】:
-
我不明白为什么这里需要模板 - 这不只是运行时多态性的一个简单示例吗?
-
你可以避免
if/else和a = someCondition ? f<Functor0>() : f<Functor1>(); -
@unapersson - 这是一个很好的问题 - 我正在尝试清理一些现有的代码,而我的问题只是在这样做时突然出现在我的脑海中 - 我相信它可以通过使用多态来解决,但无论如何我都想知道答案。 @Chris Lutz - 这只是
if/else的另一种语法,不是吗?
标签: c++ templates inheritance