我有一些(遗留)代码,如下所示:
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
}
这是非常古老的代码,我意识到这是进行此处发生的那种向下转型的糟糕方式。但这让我很好奇:为什么我不能这样写呢?
if (type == "A") {
foo_a = static_cast(foo);
} else {
foo_b = static_cast(foo);
}
它对编译器来说肯定是明确的,对我来说它看起来像是函数中的正常模板参数推导。为什么这里没有进行类型推导?
最佳答案
静态转换是危险的。在这种情况下,转换为 void 或从 void 转换为完全相同的类型。
隐式 typimg 将允许不直接与强制转换相邻的代码更改,从而使两个强制转换产生未定义的行为。
你可以编写出你想要的代码,尽管它是不明智的。
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)};
}
现在 auto_static_cast
的行为就像您希望的 static_cast
的行为一样。
关于c++ - 为什么编译器不能(或不能)推断出 static_cast 的类型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38155011/