C++ 为什么可以';t(或';t)编译器是否推导静态强制转换的类型参数?
我有一些(遗留)代码,看起来像:C++ 为什么可以';t(或';t)编译器是否推导静态强制转换的类型参数?,c++,templates,c++11,template-argument-deduction,C++,Templates,C++11,Template Argument Deduction,我有一些(遗留)代码,看起来像: 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 on
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
}
当然,它对编译器来说是明确的,对我来说,它看起来像是函数中的一个普通模板参数推断。为什么这里不进行类型推断?静态转换是危险的。在这种情况下,从空心到空心的铸件必须采用完全相同的类型 隐式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)};
}
模板
结构隐式\u静态\u转换\u t{
V V;
模板
算子T()&&{
返回静态_cast(std::forward(v));
}
};
模板
隐式\u静态\u投射\u t
自动\u静态\u转换(输入和输入){
返回{std::forward(in)};
}
现在,
自动静态施法
的行为就像你想要的那样静态施法
的行为就像。静态施法是危险的。在这种情况下,从空心到空心的铸件必须采用完全相同的类型
隐式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)};
}
模板
结构隐式\u静态\u转换\u t{
V V;
模板
算子T()&&{
返回静态_cast(std::forward(v));
}
};
模板
隐式\u静态\u投射\u t
自动\u静态\u转换(输入和输入){
返回{std::forward(in)};
}
现在
auto\u static\u cast
的行为就像你想要的那样static\u cast
的行为就像。在你看来,decltype(static\u cast(foo))或decltype(static\u cast(foo))的类型应该是什么?如果它与您所展示的语句中出现的表达式的含义不一样,那么对于泛型编程来说,这不是很可怕吗?std::string var;var=静态(事物)代码>有三个操作符=
可以强制转换为。在人们给出的许多其他原因中,静态\u强制转换(foo)
的类型应该推断为什么,我想补充一个实际问题,即您不应该经常键入单词static\u cast
来保证这样的语言功能。您认为decltype(static\u cast(foo))
或decltype(static\u cast(foo))
?如果它与您所展示的语句中出现的表达式的含义不一样,那么对于泛型编程来说,这不是很可怕吗?std::string var;var=静态(事物)代码>有三个操作符=
可以强制转换为。在人们给出的许多其他原因中,静态\u强制转换(foo)
的类型应该推断为什么,我想补充一个实际问题,即您不应该经常键入单词static\u cast
,以保证这样的语言特性。