Unpacking arguments of a functional parameter to a C++ template class

ⅰ亾dé卋堺 提交于 2020-01-20 04:05:33

问题


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

I'd like to define a template class Foo taking a single template parameter Fun

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

such that given a function like

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

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

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

Is this possible? (The use of std::tuple here is just for concreteness. More generally I'm wondering if it's possible to do something like pattern-matching on the arguments of a functional template parameter.)

The point is to avoid having to define Foo in a way like

   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 committing to a fixed number of function arguments, and requiring the argument and return types of the function to be provided explicitly as template parameters. (Defining Foo using variadic templates could presumably solve the former issue, but what about the latter?)

Thanks!


回答1:


Declare a primary template and leave it unimplemented.

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

Then provide a partial specialization that matches function types as the template argument.

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



来源:https://stackoverflow.com/questions/24948277/unpacking-arguments-of-a-functional-parameter-to-a-c-template-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!