gpt4 book ai didi

C++ 使用函数参数类型进行模板参数推导

转载 作者:太空狗 更新时间:2023-10-29 22:59:17 26 4
gpt4 key购买 nike

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);
}

跌至funcf应该能够被编译器内联,所以 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com