在VS2010中编译c++ 11中的代码时,std::function()是否检查类型

Does std::function() check the type when compiling code in C++11 in VS2010?

本文关键字:function 是否 类型 检查 std c++ 编译 VS2010 代码      更新时间:2023-10-16

我在c++ 11和VS2010的代码中使用std::function()。这是我的代码。

function<string (string)> myfunc = 3;
myfunc(string());

很明显代码是不正确的,因为myfunc对象没有正确初始化。myfunc对象应该用function<string (string)>对象赋值,而不是整数类型。当运行到代码myfunc(string());时,std::function对象抛出bad_function_call()并获得错误。

然而,让我困惑的是为什么c++ 11在编译时不检查类型?这很奇怪,因为缺乏类型检查会使程序员很容易偶然地把代码弄乱,直到运行到相应的错误行。

所以我想问:std::function()在VS2010中编译c++ 11代码时检查类型吗?如果没有,这个问题有什么解决办法吗?

看起来这是MS的std::function实现中的一个hack,允许以下内容:

function<string (string)> myfunc = NULL;

这是我可以在MS的<functional>头的实现中找到的代码:

#if defined(_NATIVE_NULLPTR_SUPPORTED) 
    && !defined(_DO_NOT_USE_NULLPTR_IN_STL)
    function(int)
    {   // construct empty function wrapper from null pointer
        this->_Reset();
    }
#endif /* defined(_NATIVE_NULLPTR_SUPPORTED) etc. */

因此,看起来这个构造函数是根据用户想要的标准一致性级别有条件地启用的。

但是,在c++ 11标准库规范中没有这样的构造函数(参见第20.8.11.2.1段)。