这与模板无关,如果T只是 typedefstd::string&而不是推导的模板参数,则会得到相同的结果:
#include <string>
typedef std::string& T;
T Foo(int & i)
{
return T(i);
}
int main()
{
int a = 1;
std::string & s = Foo(a);
}
Dietmar 的回答让我意识到这可以进一步简化为:
#include <string>
typedef std::string& T;
int main()
{
int a = 1;
std::string & s = T(a);
}
whereT(a)与演员阵容相同,(T)a即(std::string&)awhich(根据 5.4 [expr.cast] 的规则const_cast)static_cast将static_cast执行由 a const_castif that's valid (which it is not) 或 a reinterpret_castif that's valid (which it is ) 或 areinterpret_cast后跟 a const_castif that's valid,否则表达式格式错误。
所以正如 Dietmar 所说,这与做 a 是一样的reinterpret_cast,即
std::string & s = reinterpret_cast<std::string&>(a);
我发现原始代码编译非常令人惊讶,但由于它与上面那行相同,因此允许编译。但是,使用强制转换的结果是未定义的行为。
为避免令人惊讶的 whereT(a)等效于强制转换,请使用新的 C++11 统一初始化语法,T{a}它始终是初始化,而不是强制转换表达式。
很好的问题,调查和回答它向我展示了一个我以前不知道的新问题,感谢 JaredC 和 Dietmar 提供的新知识!