Context
(C++11) As part of a safeguard in a piece of serialization code, I want to check if a function pointer is known. (Otherwise, the deserialization mechanism will probably fail).
This is a (simplified) piece of code that illustrates the mechanism:
template <typename Fun>
struct FunctionCallRegistry
{
static std::unordered_map<Fun, std::string> FunctionMap()
{
static std::unordered_map<Fun, std::string> map;
return map;
}
static void Register(Fun function, std::string name)
{
auto map = FunctionMap();
auto it = map.find(function);
if (it == map.end())
{
map.insert(std::pair<Fun, std::string>(function, name));
// other code follows...
}
}
static void Ensure(Fun function)
{
auto map = FunctionMap();
auto it = map.find(function);
if (it == map.end())
{
throw std::exception("Function not found.");
}
}
};
The type of Fun here is f.ex. void (T::*fcn)(int, int).
Registration works as follows: basically for each function, I'll call Register with a function pointer and a name (which is used for the (de)serialization). There's a macro involved here and a few helper classes to do the plumbing.
Problem
When I attempt to compile this code in MSVC++, I get an error that tells me function pointers cannot be hashed:
error C2338: The C++ Standard doesn't provide a hash for this type.
In an attempt to solve this, I've tried to cast fcn to another pointer type, which doesn't seem to be allowed as well.
Question
This leaves me with the simple question: what will work? How can I check if a function pointer is registered?
Aucun commentaire:
Enregistrer un commentaire