在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!
}
这是模板化转换的工作operator
:
template <typename T>
struct dynamic_caster
{
T *ptr;
dynamic_caster(T &ref) : ptr(&ref) {}
template <typename U>
operator U &() const
{
return *dynamic_cast<std::remove_reference_t<U> *>(ptr);
}
};
template<class T>
void f1(T f2, Foo &foo)
{
f2(dynamic_caster{foo});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句