[英]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
的第一个参数自动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
。
我通常使用的功能特性代码像这样 (GPL-3行货)这样做:
template <typename F>
using first_argument_type_t =
typename sharemind::FunctionTraits<F>::template argument<0u>::type;
但也有Boost function_traits
替代方案,这可能会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.