c++ - 获取模板可调用对象的参数类型

标签 c++ templates c++11 template-meta-programming

考虑以下函数:

template<class F>
void register_handler( F& f ) // any callable object
{
   // find out T - the argument type of f
}

这里 f 是一些可调用对象,接受一个参数。它可以是函数指针、std::functionstd::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/

相关文章:

c++ - 如何获得忘记算术运算的警告?

android - 如何让 Android Studio 将我的 build.gradle 模板用于新项目?

c++ - 限制模板化类数据类型

c++ - 错误 C2672: 'operator __surrogate_func':使用 std::upper_bound 时未找到匹配的重载函数

c++ - 为什么删除复制构造函数时默认初始化会失败?

c++ - 命名构造成语和新操作符

c++ - 如何防止 GTK 按钮中的鼠标悬停效果

c++ - 使用 OpenCV 模糊保存的检测对象图像

c++ - 模板类中的模板友元函数

c++ - MSVC 用 double 支撑初始化似乎违反了标准?