Suppose I have a template that expect a function pointer:
template <typename FncPtr>
void f(FncPtr fp)
{
if constexpr ("is_first_arg_double") { // is something like this possible?
fp(1.0);
}
else if constexpr ("is_first_arg_int") { // is something like this possible?
fp(25);
}
else {
// ...
}
}
So my particular question is:
Is it possible to extract the arguments that the type FncPtr
expects and act accordingly in the template, as indicated in the code comments above?
For my particular case, I know that it will always only contain one argument, but I'd like to know if it is possible to also do this in a variadic way.
I have not been able to find anything in the reference. Closest I could get was result_of.
if it is possible to also do this in a variadic way.
Yes, it is certainly as shown below:
template<typename Ret, typename... Args> void f(Ret (*fp)(Args...))
{
if constexpr(std::is_same_v<typename std::tuple_element<0, std::tuple<Args...>>::type, double>)
{
}
else if constexpr(std::is_same_v<typename std::tuple_element<0, std::tuple<Args...>>::type, int>)
{
}
}
how about for member function pointers?
For member function pointers you can write:
template<typename Ret, typename C, typename... Args> void f(Ret (C::*fp)(Args...))
{
if constexpr(std::is_same_v<typename std::tuple_element<0, std::tuple<Args...>>::type, double>)
{
}
else if constexpr(std::is_same_v<typename std::tuple_element<0, std::tuple<Args...>>::type, int>)
{
}
}