C++ 使用函数参数类型进行模板参数推导
C++ use function argument type for template argument deduction
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
不能用
我通常使用像 this(GPL-3 许可)这样的函数特征代码来做到这一点:
template <typename F>
using first_argument_type_t =
typename sharemind::FunctionTraits<F>::template argument<0u>::type;
但还有 Boost function_traits
替代方案,这可能会有所帮助。
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
不能用
我通常使用像 this(GPL-3 许可)这样的函数特征代码来做到这一点:
template <typename F>
using first_argument_type_t =
typename sharemind::FunctionTraits<F>::template argument<0u>::type;
但还有 Boost function_traits
替代方案,这可能会有所帮助。