C ++函数式转换的目的究竟是什么或是什么? [英] What exactly is or was the purpose of C++ function-style casts?
问题描述
我在说type(value) - 风格的cast。我读过的书很快地传递过来,只是说它们在语义上等同于C风格的cast,(type)value,并且应该避免它们。如果他们的意思是一个老式的演员做同样的事情,为什么他们被添加到语言?另外,因为声明可以包含多余的括号,这段代码:T x(T(y));不做有意使用函数式cast的人会期望;它声明一个名为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);
}
这篇关于C ++函数式转换的目的究竟是什么或是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!