Question

I am using std::function() in my code with C++11 and VS2010. Here is my code.

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

It is obvious that the code is incorrect ,for the myfunc object is not initialized properly. The myfunc object should be valued by the function<string (string)> object other than the integer type. And when running to the code myfunc(string());, std::function object throws the bad_function_call() and gets error.

However,what confused me is why C++11 do not check the type during the compiling time? It is so strange because lack of type check will make programmers easily mess up the code incidentally, until running to the according error line.

So I want to ask: Does std::function() check the type when compiling code in C++11 in VS2010? If not,is there any solution to this problem?

Was it helpful?

Solution

Looks like this is a hack in MS's implementation of std::function to allow for the following:

function<string (string)> myfunc = NULL;

This is the piece of code I could find in MS's implementation of the <functional> header:

#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. */

So it looks like this constructor is enabled conditionally based on the level of standard conformance the user wants.

However, there is no such a constructor in the C++11 Standard Library specification (see paragraph 20.8.11.2.1).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top