考虑以下函数:
template<class F>
void register_handler( F& f ) // any callable object
{
// find out T - the argument type of f
}
这里 f
是一些可调用对象,接受一个参数。它可以是函数指针、std::function
或 std::bind
的结果。
问题是,如何确定f
的参数类型,并根据该类型做一些 Action ?
一个简单的解决方法是将类型显式添加到模板中,例如
template<class T, class F> // T is the argument type of F
void register_handler( F& f )
但这似乎有点过头了,因为类型 F
应该已经包含关于类型 T
的必要信息。
最佳答案
假设 F
是任何可调用类型,您无法获取其参数类型。考虑一下:
struct callable
{
void operator() (int);
void operator() (float *);
void operator() (std::string const &);
void operator() (std::list<int> &);
};
参数的类型在这里是模棱两可的。
关于c++ - 获取模板可调用对象的参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22630832/