获取模板可调用对象的参数类型 [英] Get argument type of template callable object
问题描述
请考虑以下函数:
template<class F>
void register_handler( F& f ) // any callable object
{
// find out T - the argument type of f
}
这里 f
是一些可调用对象,接受一个参数。它可以是函数指针, std :: function
或 std :: bind
的结果。
Here f
is some callable object, accepting one argument. It may be a function pointer, an std::function
or a result of std::bind
.
问题是,如何确定 f
的参数类型,并根据该类型做一些操作?
The problem is, how to determine the argument type of f
and do some actions based on that type?
一个简单的解决方法是显式地添加类型到模板,例如
An easy workaround would be to add the type to template explicitly, like
template<class T, class F> // T is the argument type of F
void register_handler( F& f )
这似乎是一个过分,因为类型 F
应该已经包含关于类型 T
的必要信息。
but this seems an overkill because type F
should already contain the necessary information about type T
.
推荐答案
假设 F
是任何可调用的类型,考虑这个:
Assuming F
is any callable type, you cannot get its argument type. Consider this:
struct callable
{
void operator() (int);
void operator() (float *);
void operator() (std::string const &);
void operator() (std::list<int> &);
};
这里的参数类型是模糊的。
the type of argument is an ambiguity here.
这篇关于获取模板可调用对象的参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!