Pergunta

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?

Foi útil?

Solução 2

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);

Outras dicas

If you see e.g. this reference of std::function assignment operator there is actually no overload that takes anything that can be NULL (often a macro defined as 0 in C++). But you can assign e.g. nullptr to a function object (as per overload 3 in the reference):

KeyFunc = nullptr;

The same with comparision, use nullptr instead of NULL. Or, as suggested by juanchopanza in a comment, use the bool cast operator.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top