vendredi 1 juillet 2016

Why can't (or doesn't) the compiler deduce the type parameter of static_cast?

I have some (legacy) code that looks like:

void castFoo(string type, void* foo) {
  FooA* foo_a = NULL;
  FooB* foo_b = NULL;

  if (type == "A") {
    foo_a = static_cast<FooA*>(foo);
  } else {
    foo_b = static_cast<FooB*>(foo);
  }

  // now do things with one of the two foo's
}

This is very old code and I realize that this is a terrible way to do the sort of downcasting that's happening here. But it made me curious: why can't I write it like this?

  if (type == "A") {
    foo_a = static_cast(foo);
  } else {
    foo_b = static_cast(foo);
  }

Surely it's unambiguous to the compiler, and it looks like a normal template argument deduction in a function to me. Why is type deduction not done here?

Aucun commentaire:

Enregistrer un commentaire