What exactly is or was the purpose of C++ function-style casts?(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);
}
这篇关于C++ 函数式强制转换的目的究竟是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 函数式强制转换的目的究竟是什么?


基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01