I want to make a std::map
with std::string
keys that contains functions.
These functions should be templates
in order to work with different numeric values:
template <typename T> T (*pfunc)(T,T);
The map declarations looks like this:
std::map<std::string, pfunc> funcMap;
I know I need a template argument list for pfunc
but I don't really know how to do it.
[EDIT]
Taking in count the comments. I would like to be able to: Create a function template as:
template <typename T>
T myMax(T x, T y)
{
return (x > y)? x: y;
}
or
template <typename T>
T myMin(T x, T y)
{
return (x < y)? x: y;
}
funcMap["myMax"] = myMax;
or funcMap["myMin"] = myMin;
funcMap["myMax"]<int>(3,4);
funcMap["myMax"]<float>(3.1,4.5);
funcMap["myMin"]<int>(3,4);
funcMap["myMin"]<float>(3.1,4.5);
I think the best you will get is
template <typename T>
T myMax(T x, T y)
{
return (x > y)? x: y;
}
template <typename T>
T myMin(T x, T y)
{
return (x < y)? x: y;
}
template <typename T> using pfunc = T(*)(T, T);
template <typename T> std::map<std::string, pfunc<T>> funcMap = {
{ "myMax", myMax },
{ "myMin", myMin }
};
You will need to define all your function templates before defining funcMap, or limit yourself to a pre-determined set of types. I don't know of a way of populating infinite funcMap
instantiations with infinite function template instantiations after it's definition.