简体   繁体   English

为什么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); 
}

My C++ compiler is VS 2015 Update 3. 我的C ++编译器是VS 2015 Update 3。

I just wonder: 我只是好奇:

Why doesn't the C++ standard allow std::function<int(int)> fn3 = static_cast<int(int)>(f); 为什么C ++标准不允许std::function<int(int)> fn3 = static_cast<int(int)>(f); ?

What's the rationale behind? 背后的原理是什么?

This is presumably because you cannot have an object of function type (under the definition of object used in the standard: a region of storage). 据推测这是因为您不能具有功能类型的对象(在标准中使用的对象的定义下:存储区域)。 The cast would need to create an object of the type int(int) , but you can't have objects of that type (functions are not objects). 强制转换将需要创建一个类型为int(int)的对象,但是您不能具有该类型的对象(函数不是对象)。

You can, however, cast to a function pointer because you can have objects of a function pointer type. 但是,您可以强制转换为函数指针,因为您可以拥有函数指针类型的对象。 In fact, the function argument to static_cast already decays to a function pointer before being casted to the now-same type (much like an array readily decays to a pointer). 实际上, static_cast的函数参数在转换为现在相同的类型之前已经衰减为函数指针(很像数组很容易衰减为指针)。 This is because of [expr.static.cast]/8: 这是因为[expr.static.cast] / 8:

The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) conversions are applied to the operand. 左值到右值(4.1),数组到指针(4.2)和函数到指针(4.3)转换应用于操作数。

Long story short, fn2 is equivalent to fn1 with a redundant cast because f is already converted to a function pointer when intializing fn1 . 长话短说, fn2等效于使用冗余fn1转换的fn1 ,因为初始化fn1f已被转换为函数指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM