【发布时间】:2021-04-19 21:18:11
【问题描述】:
在f1() 中,我希望能够将其foo 参数动态转换为与f2() 的参数相同的类型(Bar、Qux 等)。这可能吗?
struct Foo {
virtual ~Foo() = default;
};
struct Bar : public Foo {};
struct Qux : public Foo {};
template<class T>
void f1(T f2, Foo &foo) {
// dynamically cast foo to type of f2's argument?
f2(dynamic_cast<Bar &>(foo));
}
int main() {
Bar bar;
Qux qux;
f1([](Bar &bar) {}, bar);
f1([](Qux &qux) {}, qux); // error here!
}
【问题讨论】:
-
这是我今年迄今为止最喜欢的问题之一。表面上看起来很简单,但是......不 - 看看所有不错的答案。全方位 +1。
标签: c++ c++11 templates casting dynamic-cast