C++:是否可以使用带有模板参数的动态绑定?
我有一个模板函数,它接受函数对象(“函子”)作为模板参数:
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
并在运行时决定什么(派生)类型作为模板参数传递?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
?这根本不可能。在代码中的某些时候,您需要区分大小写。当然,这并不需要手动编写;您可以使用宏(或模板)来生成必要的代码。但它必须存在。
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.
避免检查的一种方法(如果这确实是您想要做的),是使用数组 - ..
现在 - 使用
someCondition
作为索引。这仅依赖于运行时多态性,而不是您正在使用的冗余模板机制...(顺便说一句,不要忘记清理!)
当然,这是令人讨厌且坦率地说是多余的,
if< 的开销/code> 无关紧要,但它为代码添加的清晰度却很重要......
One way to avoid the check (if that is REALLY what you want to do), is to use an array - ..
now - use
someCondition
as an index.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...