【发布时间】:2016-05-25 07:49:09
【问题描述】:
template<typename T>
void f(void (*func)(const T&)) {
(*func)(T());
}
void func(const int& i) {
std::cout << i << std::endl;
}
int main() {
f(&func);
}
这里f的模板参数T (= int)是根据函数func的第一个参数自动扣除的。
这也可以扩展为与通用函子(lambda 函数或其他函数对象)一起使用。可能与第二个函数一起使用,即类似的东西
template<typename T, typename Function> void f(Function func);
template<typename Function>
void call_f(Function func) {
using arg_type = first_argument_type_t<Function>; // ???
f<arg_type, Function>(func);
}
f 中落入func 应该可以被编译器内联,所以不能使用std::function。
【问题讨论】:
-
推导参数类型需要考虑很多情况。
-
你不会在一般情况下使用它,即,如果该仿函数是通用 lambda,或者具有重载/模板化的类类型实例
operator()
标签: c++ templates c++11 c++14 functor