如何获取可变参数模板类中的函数指针的参数类型? [英] How do I get the argument types of a function pointer in a variadic template class?
问题描述
这是此问题的后续:函数的泛型函子与任何参数列表
我有这个functor类(全代码见上面的链接):
I have this functor class (full code see link above):
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...); }
};
在operator()中,我可以使用递归剥离函数轻松访问args ...请在此处 http://www2.research.att.com/~bs/C ++ 0xFAQ.html#variadic-templates
In operator() I can access the args... easily with a recursive "peeling" function as described here http://www2.research.att.com/~bs/C++0xFAQ.html#variadic-templates
我的问题是:我想访问f的参数类型,即ARGS ...,在构造函数中。显然我不能访问值,因为没有到目前为止,但参数类型列表以某种方式在f中插入,不是吗?
My problem is: I want to access the types of the arguments of f, i.e. ARGS..., in the constructor. Obviously I can't access values because there are none so far, but the argument type list is somehow burried in f, isn't it?
推荐答案
您可以写如下所示的 function_traits
类,以发现参数类型,返回类型和参数数量:
You can write function_traits
class as shown below, to discover the argument types, return type, and number of arguments:
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;
};
};
测试代码:
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;
}
这篇关于如何获取可变参数模板类中的函数指针的参数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!