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);
}
这里的模板参数T (= int)
的f
基础上,函数的第一个参数被自动扣除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);
}
秋天func
的f
应该可以被编译器内联,所以std::function
不能使用。
我通常使用的功能特性代码像这样(GPL-3行货)这样做:
template <typename F>
using first_argument_type_t =
typename sharemind::FunctionTraits<F>::template argument<0u>::type;
但是也有Boostfunction_traits
替代方案,可能会有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句