如何在可变参数模板类中获取函数指针的参数类型?

ste*_*fen 31 c++ function-pointers functor variadic-templates c++11

这是这个问题的后续问题:具有任何参数列表的函数的泛型函子

我有这个仿函数类(完整代码见上面的链接):

template<typename... ARGS>
class Foo
{
    std::function<void(ARGS...)> m_f;
  public:
    Foo( std::function<void(ARGS...)> f ) : m_f(f) {}
    void operator()(ARGS... args) const { m_f(args...); }
};
Run Code Online (Sandbox Code Playgroud)

在operator()中,我可以使用递归的"剥离"功能轻松访问args ...如http://www2.research.att.com/~bs/C++0xFAQ.html#variadic-templates

我的问题是:我想在构造函数中访问f的参数类型,即ARGS ....显然我无法访问值,因为到目前为止还没有,但参数类型列表以某种方式埋没在f中,不是吗?

Naw*_*waz 62

您可以编写function_traits如下所示的类,以发现参数类型,返回类型和参数数量:

template<typename T> 
struct function_traits;  

template<typename R, typename ...Args> 
struct function_traits<std::function<R(Args...)>>
{
    static const size_t nargs = sizeof...(Args);

    typedef R result_type;

    template <size_t i>
    struct arg
    {
        typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
    };
};
Run Code Online (Sandbox Code Playgroud)

测试代码:

struct R{};
struct A{};
struct B{};

int main()
{
   typedef std::function<R(A,B)> fun;

   std::cout << std::is_same<R, function_traits<fun>::result_type>::value << std::endl;
   std::cout << std::is_same<A, function_traits<fun>::arg<0>::type>::value << std::endl;
   std::cout << std::is_same<B, function_traits<fun>::arg<1>::type>::value << std::endl;
} 
Run Code Online (Sandbox Code Playgroud)

演示:http://ideone.com/YeN29

  • 意思号上的死链接 (5认同)

归档时间:

查看次数:

16345 次

最近记录:

13 年,9 月 前