为什么C++不允许static_cast<function_type_of_f>(f)?

Why doesn't C++ allow to static_cast<function_type_of_f>(f)?

本文关键字:gt C++ of type 不允许 cast lt 为什么 function static      更新时间:2023-10-16
#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时已经转换为函数指针