lundi 19 avril 2021

Dynamically cast to function argument type (C++)

In f1(), I want to be able to dynamically cast its foo argument to the same type as the argument of f2() (Bar, Qux, etc). Is this possible?

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!
}

Aucun commentaire:

Enregistrer un commentaire