为什么C++不允许static_cast<function_type_of_f>(f)?
Why doesn't C++ allow to static_cast<function_type_of_f>(f)?
#include <functional>
int f(int x)
{
return 0;
}
int main()
{
std::function<int(int)> fn1 = f; // ok
std::function<int(int)> fn2 = static_cast<int(*)(int)>(f); // ok
//
// error C2066: cast to function type is illegal
//
std::function<int(int)> fn3 = static_cast<int(int)>(f);
}
我的c++编译器是VS 2015 Update 3.
我只是想知道:
为什么c++标准不允许std::function<int(int)> fn3 = static_cast<int(int)>(f);
?
背后的原理是什么?
这可能是因为您不能拥有函数类型的对象(根据标准中使用的对象定义:存储区域)。强制转换需要创建类型为int(int)
的对象,但是不能拥有该类型的对象(函数不是对象)。
类型转换为函数指针,因为可以有函数指针类型的对象。事实上,static_cast
的函数参数在被转换为现在相同的类型之前已经衰变为函数指针(很像数组容易衰变为指针)。这是因为[expr.static.cast]/8:
操作数适用左值到右值(4.1)、数组到指针(4.2)和函数到指针(4.3)的转换。
长话短说,fn2
相当于fn1
的冗余强制转换,因为f
在初始化fn1
时已经转换为函数指针
相关文章:
- EASTL矢量<向量<int>>连续的
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- C 字符串比较“祝您好运”&gt;“再见”
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- C 操作员&gt;&gt;与突变器过载
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 是否需要使用 - &gt;运算符在C 中调用成员函数时
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- 错误c++visual studio c2227左侧'->;Init';必须指向类/结构/联合/泛型类型
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- ``这个''不能用this-&gt;指针变量
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是std :: set&lt; std :: future&gt;不可能存在
- 使用shared_ptr<字符串>转换为一个无序集合<字符串>
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到