I am fighting with this variadic template for a long time. Could anyone help me please? I would like to build an executor that is able to call cmath functions and pass all its parameters through vector. Please consider a following code:
bool execute(const std::string &functionName, const std::vector<double> ¶ms)
{
if (functionName == "cos") return execute(cos, params);
if (functionName == "atan2") return execute(atan2, params);
return false;
}
Function cos
takes one parameter while atan2
takes two. I wanted to have something like this:
template <typename... Types>
bool execute(double (*func)(Types...), const std::vector<double> ¶ms)
{
if (params.size() != sizeof...(Types)) {
errorString = "Wrong number of function arguments";
return false;
}
errno = 0;
result = func(params[0]);
errorString = strerror(errno);
return !errno;
}
However, I encountered two problems:
cos
works for both double
and float
, so call is ambiguous. Moreover, I cannot use double
in place of typename
to force it. Or there is other way?func
how can I specify right amount of arguments from vector depending on type of function?Or maybe there is something already available in C++ which I do not know about? :) Many Thanks!
You might use std::index_sequence
, something like:
template <typename... Types, std::size_t ... Is>
double execute(double (*func)(Types...),
const std::vector<double> ¶ms,
std::index_sequence<Is...>)
{
if (params.size() != sizeof...(Types)) {
throw std::runtime_error("Wrong number of function arguments");
}
return func(params[Is]...);
}
template <typename... Types>
double execute(double (*func)(Types...), const std::vector<double> ¶ms)
{
return execute(func, params, std::index_sequence_for<Types...>());
}
And call it (specify template argument to fix overload).
double execute(const std::string &functionName, const std::vector<double> ¶ms)
{
if (functionName == "cos") return (execute<double>)(cos, params);
if (functionName == "atan2") return (execute<double, double>)(atan2, params);
throw std::runtime_error("Unknown function name");
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments