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
无法使用。
最佳答案
我通常使用像 this 这样的函数特征代码(GPL-3 许可)这样做:
template <typename F>
using first_argument_type_t =
typename sharemind::FunctionTraits<F>::template argument<0u>::type;
但是还有 Boost function_traits
替代方案,这可能会有帮助。
关于C++ 使用函数参数类型进行模板参数推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37430898/