C ++ function type argument template parameter

I want to be able to call a function with a template parameter that has a function type (including parameter types and return types), i.e. double(int, long) , and the functions separate the types and use them individually.

For example, I want to be able to call a function

 printRes<double(int, long)>(); 

This function above should parse the template argument and extract the return type double and output it.

I know how to do this using a class and variable templates:

 #include <iostream> #include <typeinfo> template <typename T> class A {}; template <typename Res, typename... Args> class A<Res (Args...)> { // Parse template argument public: void printRes() { std::cout << typeid(Res).name() << std::endl; } }; 

Then I can use it as follows:

 int main() { A<double(int, long)> a; a.printRes(); } 

What outputs:

 d 

I want to do this using a simple function. Here is what I came up with:

 template <typename Res, typename... Args> void printRes() { std::cout << typeid(Res).name() << std::endl; } 

However, now I have to specify template options such as this:

 int main() { printRes<double, int, long>(); } 

Is there a way to implement this function so that it can be called using the same template parameter as the class version (i.e. double(int, long) )?

+3
c ++ c ++ 11 templates variadic-templates
source share
1 answer

I think you are almost there. You can use your own trait inside the function template. Here is a possible implementation:

 #include <iostream> #include <typeinfo> template <typename T> struct A { }; template<typename Res, typename... Args> struct A<Res (Args...)> { using type = Res; }; template<typename T> void printRes() { using Res = typename A<T>::type; std::cout << typeid(Res).name() << std::endl; } int main() { printRes<double(int, long)>(); } 

And here is a living example .

+3
source share

All Articles