Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extracting function parameter types from templated function

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have not been able to find anything in the reference. Closest I could get was result_of.

>Solution :

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>)
      {
      }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading