Unpacking function parameter arguments into a C ++ template class

I have a question related to functional template arguments for template classes in C ++.

I would like to define a Foo template class using a single Fun template parameter

  template <typename Fun> struct Foo { ... }; 

such that for a given function of type

  void bar(std::string a, float b, char c) { ... } 

then Foo<bar>::args_t will be equivalent to typedef for

  std::tuple<std::string, float, char> 

Is it possible? (The use of std::tuple here is for concreteness only. In general, I wonder if something like matching patterns in function parameter arguments is possible.)

The point is not to define Foo in such a way as

  template Foo<typename A, typename B, typename C, typename D, D (*Fun)(A a, B b, C c)> struct Foo { typedef std::tuple<A,B,C> args_t; }; 

which requires both fixing a fixed number of function arguments, and requiring arguments and return function types, which must be explicitly specified as template parameters. (Defining Foo using variable templates might seem to solve the former question, but what about the latter?)

Thanks!

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

Declare the main template and leave it incomplete.

 template<typename T> struct foo; // unimplemented primary template 

Then specify a partial specialization that matches function types as an argument to the template.

 template<typename Result, typename... Args> struct foo<Result(Args...)> { using args_t = std::tuple<Args...>; }; 

You can access the nested type as

 foo<decltype(bar)>::args_t 

Live demo

+11
source share

All Articles