Search code examples
c++visual-studio-2010visual-studio-2012c++11std-function

Updated vs 2010 solution to 2012. std::function = NULL error


I just imported a 2010 vs solution into 2012.

Now when I compile the program (that successfully compiled on 2010) fails with several errors, for example:

 c:\users\frizzlefry\documents\visual studio 2010\projects\menusystem\menusystem\ktext.cpp(288) : see reference to function template instantiation 'std::function<_Fty> &std::function<_Fty>::operator =<int>(_Fx &&)' being compiled
1>          with
1>          [
1>              _Fty=void (void),
1>              _Fx=int
1>          ]

Going to line 288 in KText.cpp is in this function:

void KText::OnKeyUp(SDLKey key, SDLMod mod, Uint16 unicode) {
    IsHeld.Time(500);       //Reset first repeat delay to 500 ms.
    IsHeld.Enable(false);   //Turn off timer to call the IsHeld.OnTime function.
    KeyFunc = NULL;     //LINE 288  //Set keyFunc to NULL 
}

I've checked a handful of them and they are all related to setting std::function<void()> func to NULL.

Clearly I can go through and change a buncha lines but my program is set up in a way that checks:

if(func != NULL) func();

How can I replace this sort of feature?


Solution

  • I'd prefer letting the library decide what is the default-constructed value for the function<> instance:

    KeyFunc = {}; // uniform initialization (c++11)
    // or
    KeyFunc = KeyFuncType(); // default construct
    

    Demo with asserts: See it Live on Coliru

    #include <functional>
    #include <cassert>
    
    int main()
    {
        using namespace std;
    
        function<int(void)> f = [] { return 42; };
    
        assert(f);
        assert(42 == f());
    
        f = nullptr;
        assert(!f);
    
        f = {};
        assert(!f);
    }
    

    If your compiler doesn't have the chops for uniform initialization, use a typedef:

    typedef function<int(void)> Func;
    
    Func f = [] { return 42; };
    assert(f);
    
    f = Func();
    assert(!f);