C++ 函数式强制转换的目的究竟是什么?
我说的是类型(值)"风格的转换.我读过的书很快就忽略了它们,只说它们在语义上等同于 C 风格的强制转换,(类型)值",并且应该避免它们.如果它们的意思与旧式演员表的意思相同,为什么还要将它们添加到语言中?此外,因为声明可以包含多余的括号,这个代码:T x(T(y));"不会做打算使用函数式强制转换的人所期望的;它声明了一个名为 x 的函数,它接受一个 T 并返回一个 T,而不是通过将 y 强制转换为 T 来构造一个名为 x 的 T 变量.
I am talking about "type(value)"-style casts. The books I have read pass over them quickly, saying only that they are semantically equivalent to C-style casts, "(type) value", and that they should be avoided. If they mean the same thing an old-style cast does, why were they ever added to the language? Also, because declarations can contain superfluous parentheses, this code: "T x(T(y));" doesn't do what someone intending to use the function-style casts would expect; it declares a function named x accepting a T and returning a T rather than constructing a T variable named x by casting y to a T.
他们是语言设计的错误吗?
Were they a mistake in the design of the language?
推荐答案
函数样式转换为原始类型和用户定义类型带来了一致性.这在定义模板时非常有用.举个很傻的例子:
Function style casts bring consistency to primitive and user defined types. This is very useful when defining templates. For example, take this very silly example:
template<typename T, typename U>
T silly_cast(U const &u) {
return T(u);
}
我的 silly_cast
函数适用于原始类型,因为它是函数风格的强制转换.它也适用于用户定义的类型,只要类 T 有一个采用 U 或 U const & 的单参数构造函数.
My silly_cast
function will work for primitive types, because it's a function-style cast. It will also work for user defined types, so long as class T has a single argument constructor that takes a U or U const &.
template<typename T, typename U>
T silly_cast(U const &u) {
return T(u);
}
class Foo {};
class Bar {
public:
Bar(Foo const&) {};
};
int main() {
long lg = 1L;
Foo f;
int v = silly_cast<int>(lg);
Bar b = silly_cast<Bar>(f);
}
相关文章