Checking if the function std :: is assigned to nullptr

I am wondering if there is a way to check if the function pointer assigned to you in std::function , nullptr . I expected that ! -operator will do this, but it only works when something like nullptr_t assigned to the function.

 typedef int (* initModuleProc)(int); initModuleProc pProc = nullptr; std::function<int (int)> m_pInit; m_pInit = pProc; std::cout << !pProc << std::endl; // True std::cout << !m_pInit << std::endl; // False, even though it clearly assigned a nullptr m_pInit = nullptr; std::cout << !m_pInit << std::endl; // True 

I wrote this helper function to get around this now.

 template<typename T> void AssignToFunction(std::function<T> &func, T* value) { if (value == nullptr) { func = nullptr; } else { func = value; } } 
+6
source share
1 answer

This is a mistake in your implementation of std::function (and also, apparently, for me), the standard says operator! returns true if the object is constructed with a pointer to a null function, see [func.wrap.func] 8. The assignment operator should be equivalent to constructing std::function with an argument and its replacement, therefore operator! should also return true in this case.

+8
source

Source: https://habr.com/ru/post/951059/


All Articles