Patrick Collins
Patrick Collins

Reputation: 10584

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?

Upvotes: 0

Views: 306

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275585

Static cast is dangerous. In this case, casting to/from void must go to the exact same type.

Implicit typimg would allow code changes not directly adjacent to the casts to make the two casts generate undefined behaviour.

You can make code that does what you want, as ill advised as it is.

template<class V>
struct implicit_static_cast_t{
  V v;
  template<class T>
  operator T()&&{
    return static_cast<T>(std::forward<V>(v));
  }
};

template<class In>
implicit_static_cast_t<In>
auto_static_cast(In&& in){
  return {std::forward<In>(in)};
}

Now auto_static_cast behaves like you want static_cast behaves like.

Upvotes: 3

Related Questions